mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-01 18:07:00 +01:00
Merge origin/master and renumber additive Speko migrations
Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
commit
bf1ead3772
65 files changed
+5336
-56682
No files matched your search
@@ -19,6 +19,17 @@ That's it. On first start the server:
|
||||
|
||||
Data persists across restarts in `~/.paperclip/instances/default/db/`. To reset local dev data, delete that directory.
|
||||
|
||||
Subscription reporting adds `ai_subscriptions` (company-scoped account identity),
|
||||
`ai_subscription_prices` (immutable price revisions), and
|
||||
`ai_subscription_connections` (selected grant-to-account bindings). New managed
|
||||
subscription receipts also have a nullable `cost_events.subscription_id`.
|
||||
Migration `0322_reflective_kree.sql` is replay-safe and leaves existing cost
|
||||
amounts and receipts untouched. No historical account attribution is inferred.
|
||||
Deleting a connection removes its binding but retains subscription price history;
|
||||
disconnecting is not proof that provider billing ended. See
|
||||
[subscription cost reporting](connections/AI-CONNECTIONS.md#subscription-cost-reporting)
|
||||
for the reporting and ownership rules.
|
||||
|
||||
If you need to apply pending migrations manually, run:
|
||||
|
||||
```sh
|
||||
|
||||
+11
-1
@@ -1271,7 +1271,7 @@ It owns bounded run projections, database encoding checks, task session reads an
|
||||
writes, explicit resumes, session compaction, and usage/billing helpers.
|
||||
`createHeartbeatRunState(db)` binds these operations without doing database work
|
||||
during construction. The encoding-check cache belongs to each factory instance.
|
||||
`heartbeat.ts` keeps run execution and session-goal recovery, and re-exports the
|
||||
`heartbeat.ts` keeps run execution and re-exports the
|
||||
existing public helpers. Keep session policy changes separate from run
|
||||
orchestration changes.
|
||||
|
||||
@@ -1321,6 +1321,16 @@ Forwarding callbacks preserve construction order for budget, retry, recovery,
|
||||
and queue services. Existing public helpers remain re-exported by `heartbeat.ts`.
|
||||
Keep cancellation policy changes separate from this extraction and execution.
|
||||
|
||||
Scheduling is in `server/src/services/heartbeat/scheduling.ts`. It owns timer
|
||||
ticks, issue-monitor claims and dispatch, exhausted-monitor recovery, and
|
||||
session-goal recovery. `createHeartbeatScheduling` binds explicit dependencies
|
||||
without querying or starting timers. Queue admission, heartbeat policy parsing,
|
||||
and atomic timer claims stay in `queue.ts`; the service supplies those operations
|
||||
and the current scheduling-suppression and worktree-cutoff callbacks. Monitor
|
||||
claims remain database-scoped so separate scheduler instances cannot dispatch
|
||||
the same claim. The public heartbeat methods keep their existing signatures.
|
||||
Keep scheduling policy changes separate from this extraction and execution.
|
||||
|
||||
## Wake Context Delivery
|
||||
|
||||
Built-in adapters deliver wake context through the run prompt, including structured
|
||||
|
||||
@@ -717,3 +717,120 @@ requires a complete `response_wake` object.
|
||||
|
||||
Task-card account repair uses the provider reconnect form for routed accounts,
|
||||
retaining the saved endpoint, protocol, model aliases, and connection identity.
|
||||
|
||||
## Subscription cost reporting
|
||||
|
||||
The Costs page shows metered API spend beside the **current monthly subscription
|
||||
commitment**. API dollars and both token totals follow the selected date range;
|
||||
monthly subscription fees do not. Tokens measure Paperclip work only, while a
|
||||
subscription fee covers the entire provider account, including other usage.
|
||||
Recorded subscription overages remain separate from the recurring fee.
|
||||
|
||||
Agent, user, project, and model cost rows use a right-aligned amount with any
|
||||
estimate badge underneath. Each badge reflects that row's own ledger events in
|
||||
the selected date range.
|
||||
|
||||
Discovery uses the managed AI connection actually selected for a run, or the
|
||||
connected accounts visible to the user viewing Costs. An administrator cannot
|
||||
probe another user's private credentials. OpenAI identity combines workspace and
|
||||
seat claims from the exact bearer token accepted by its usage endpoint, with
|
||||
the selected workspace checked against those claims. An editable ID token cannot
|
||||
establish identity or grant price-edit access. Claude's OAuth profile combines
|
||||
organization and account identity when the token allows profile access. Identity
|
||||
keys are company-scoped hashes; reporting never exposes tokens, raw provider IDs,
|
||||
or credential hashes. Multiple agents and connections sharing a known paid seat
|
||||
count once. Distinct seats remain separate even in the same workspace. Before
|
||||
provider verification, each connection grant has its own unconfirmed record;
|
||||
local claims alone cannot combine another user's account or billing editors.
|
||||
|
||||
Supported exact plan identifiers with a stable account identity map to dated, USD, before-tax web list prices
|
||||
in `packages/shared/src/subscriptions.ts`. The UI labels these **Estimated** (or
|
||||
**Partially estimated** when combined with user-supplied prices). A generic
|
||||
OpenAI Pro, Claude Max, team, or enterprise entitlement does not reliably
|
||||
identify the price: it stays **Price unknown** until its owner enters an amount.
|
||||
Annual prices are divided by 12 using exact decimal arithmetic. Supported
|
||||
currencies are totaled separately; Paperclip does not estimate exchange rates.
|
||||
|
||||
Use **Subscriptions → View details → Edit price** to record the amount paid,
|
||||
billing cadence, and tracking status. Personal prices are editable by their
|
||||
owner; shared prices require AI-connection management permission. When the same
|
||||
seat is connected both personally and shared, both its personal owners and
|
||||
company connection managers can edit the single fee, regardless of discovery
|
||||
order. These billing permissions survive disconnecting a connection; they do
|
||||
not grant access to its credentials. Viewers cannot
|
||||
edit. Updates append an immutable price revision and reject stale concurrent
|
||||
edits. Ending or excluding tracking does not cancel the provider subscription.
|
||||
Disconnecting a connection also does not prove that billing stopped, so the fee
|
||||
continues until explicitly ended or excluded.
|
||||
|
||||
Claude setup tokens can lack profile permission. Grok plan observations currently
|
||||
do not supply a verified billing identity. Such connections retain an unconfirmed
|
||||
identity and may need manual linking after a credential change. An unconfirmed
|
||||
identity requires a user-supplied price before contributing a monthly fee, so
|
||||
credential rotations cannot multiply automatic list-price estimates. **Link accounts**
|
||||
combines usage and keeps the selected account's price; it is restricted to accounts
|
||||
the caller can edit and should only join the same subscription or paid seat.
|
||||
Provider observations never overwrite a user-supplied price. Conflicting manual
|
||||
prices prevent automatic linking rather than silently choosing one.
|
||||
|
||||
Monthly totals and account details include only accounts the viewer may see:
|
||||
personal billing owners, company managers of shared fees, and the authorized
|
||||
audience of active shared grants. Revoking a grant removes its audience's access
|
||||
to the fee. Cost-read permission alone does not reveal
|
||||
another member's personal plan, price, owner, or account-linked activity. Billing
|
||||
editors retain visibility after disconnection so they can end tracking. Aggregate
|
||||
API and subscription run-token totals remain company-wide, as in existing cost
|
||||
reports; hidden private accounts are not mislabeled as missing attribution.
|
||||
Fixed-price, credit-billed, and unknown usage remain in the inference ledger.
|
||||
They are reported separately from API and subscription tokens as other or unknown
|
||||
billing types; the API retains the `unknown` field name for this combined total.
|
||||
|
||||
Provider lookups run in the background, with a six-hour attempt cache shared by
|
||||
server replicas, at most four active provider lookups per process, a 15-second
|
||||
request deadline, and a 256 KiB response limit. Failed checks preserve the last
|
||||
observed plan and price. The report reads the database only and loads just the
|
||||
current price for each account; earlier revisions remain stored for auditing.
|
||||
Accepted discovery requests wait for provider capacity instead of skipping accounts.
|
||||
At most twenty discovery requests run per process; additional requests receive
|
||||
HTTP 429 and can be retried using **Retry account check**.
|
||||
Failed background UI reloads retain the last loaded values and show a short
|
||||
status message. Failed discovery offers **Retry account check**.
|
||||
|
||||
Each new managed subscription run snapshots its subscription ID. Its cost receipt
|
||||
inherits that server-derived ID, outside the immutable monetary receipt hash.
|
||||
Switching accounts cannot move an earlier run to the new subscription. Linking
|
||||
duplicates resolves historical IDs in reports without rewriting receipts.
|
||||
Legacy and unmanaged subscription usage still contributes to the subscription
|
||||
token total but is not retroactively assigned to a guessed account. Subscription
|
||||
estimates never create finance events, change the inference ledger's dollar
|
||||
amounts, or consume agent budgets.
|
||||
|
||||
The company-scoped API is documented in OpenAPI:
|
||||
|
||||
- `GET /api/companies/:companyId/costs/subscriptions`: current fees and usage for
|
||||
`from`/`to` (inclusive, matching existing cost reports), or `period=all`.
|
||||
- `POST /api/companies/:companyId/costs/subscriptions/refresh`: request background
|
||||
discovery for the caller's authorized connections; returns `202` immediately.
|
||||
- `PATCH /api/companies/:companyId/costs/subscriptions/:subscriptionId`: save a
|
||||
price with `expectedRevision`, plan, nullable `amountCents`, currency, cadence,
|
||||
and tracking status.
|
||||
- `POST /api/companies/:companyId/costs/subscriptions/:subscriptionId/link`: link
|
||||
a duplicate using `targetId`, `expectedRevision`, and `targetRevision`.
|
||||
|
||||
Storybook **Costs / Subscriptions** renders the production Costs page with
|
||||
interactive fixtures for normal estimates, unknown prices, provider failures,
|
||||
and mobile layouts. Its edits affect fixture data only. Focused verification:
|
||||
|
||||
```sh
|
||||
pnpm exec vitest run server/src/__tests__/subscriptions.test.ts \
|
||||
server/src/__tests__/subscription-routes.test.ts \
|
||||
ui/src/components/SubscriptionCostCard.test.tsx ui/src/pages/Costs.test.tsx
|
||||
pnpm check:token-gates
|
||||
pnpm storybook
|
||||
```
|
||||
|
||||
These tests include real PostgreSQL persistence, migration replay, concurrent
|
||||
updates, account changes, duplicate identity resolution, ownership, monetary
|
||||
receipt replay, unknown prices, and failed provider observations. Provider payloads
|
||||
are fixtures; live provider access still depends on the deployment's credentials
|
||||
and scopes.
|
||||
@@ -6,9 +6,10 @@ owns the assignment lifecycle and durable tool receipts. Dot uses Paperclip's
|
||||
existing agent permissions and task tools, including document writes and
|
||||
completion feedback.
|
||||
|
||||
This first version supports a self-hosted instance with a local Runner
|
||||
controller and a stable public HTTPS origin. Hosted agent-broker and remote
|
||||
controller deployments are not qualified. The feature is off by default.
|
||||
Dot supports a self-hosted instance with a local Runner controller and a stable
|
||||
public HTTPS origin, or a Cloud instance with a managed sandbox Runner and the
|
||||
tenant Dot ingress. The feature is off by default. Cloud requires the native
|
||||
Runner setting in addition to Dot and Assistant connections (MCP).
|
||||
|
||||
## Enable and pair
|
||||
|
||||
@@ -418,6 +419,12 @@ The setup prompt asks Dot to upload its own current image only if it can obtain
|
||||
|
||||
### Invite from the agent picker
|
||||
|
||||
A new Dot remains in hire preparation until pairing and the event check finish.
|
||||
Setup can issue its prompt during preparation and verification; the compatibility
|
||||
status `paused` does not require an operator resume in these states. The live
|
||||
checks continue until the binding and agent lifecycle are both ready. A manual
|
||||
pause or pending hire approval still blocks setup.
|
||||
|
||||
Enable **OpenAI Dot** and **Assistant connections (MCP)**, then choose **New Agent → Invite an external agent → Dot**. Copy the setup prompt into your Dot. Paperclip creates a scoped Runner agent and watches connection, event subscription, and a harmless event round trip. If your company requires hire approval, approve the agent before copying its pairing prompt. The test event is sent automatically after the callback is verified; Retry test event remains available if confirmation times out.
|
||||
|
||||
Reopening setup resumes the operator's unfinished invitation. Pairing codes are not stored in browser persistence. After refreshing or when an open prompt expires, setup automatically prepares a fresh prompt to copy. It first checks current connection state and replaces only the pending capability, without revoking an established connection. A failed renewal offers a retry rather than looping. If another browser window replaces the prompt, the current window asks before replacing it again. Hermes and Other continue to use the ordinary external-agent invitation flow.
|
||||
@@ -447,3 +454,12 @@ pnpm exec vitest run server/src/__tests__/dot-runner.test.ts -t 'private Daytona
|
||||
```
|
||||
|
||||
The fixture creates a private, bounded sandbox and deletes it in `finally`. Default tests do not contact Daytona. This test uses a scripted MCP client; a separate real OpenAI Dot walkthrough is required to qualify provider behavior.
|
||||
|
||||
### Public Cloud consent
|
||||
|
||||
The Dot consent page is intentionally accessible without a Paperclip board
|
||||
session. Background UI probes may receive `tenant_session_required` or
|
||||
`tenant_session_invalid` there; they must not reload the public consent document.
|
||||
The public request and pairing endpoints still enforce the OAuth request and
|
||||
one-use pairing code. Normal board routes retain Cloud session recovery, and
|
||||
archived stacks still redirect through a document reload.
|
||||
@@ -55,6 +55,9 @@ describeEmbeddedPostgres("connections v3 schema core migration", () => {
|
||||
// Managed-account observations are later consumers of the same connection key.
|
||||
await sql`DROP TABLE IF EXISTS "tool_connection_app_syncs"`;
|
||||
await sql`DROP TABLE IF EXISTS "tool_connection_app_snapshots"`;
|
||||
// Subscription reporting adds a later grant binding; rewind the empty
|
||||
// fixture table before recreating grants, preserving production FK checks.
|
||||
await sql`DROP TABLE IF EXISTS "ai_subscription_connections"`;
|
||||
await sql`DROP TABLE IF EXISTS "connection_grants"`;
|
||||
await sql`DROP INDEX IF EXISTS "tool_connections_company_uid_uq"`;
|
||||
await sql`ALTER TABLE "tool_connections" DROP CONSTRAINT IF EXISTS "tool_connections_company_id_uq"`;
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
CREATE TABLE IF NOT EXISTS "ai_subscription_connections" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"company_id" uuid NOT NULL,
|
||||
"connection_id" uuid NOT NULL,
|
||||
"grant_id" uuid NOT NULL,
|
||||
"credential_key" text NOT NULL,
|
||||
"subscription_id" uuid NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE IF NOT EXISTS "ai_subscription_prices" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"company_id" uuid NOT NULL,
|
||||
"subscription_id" uuid NOT NULL,
|
||||
"revision" integer NOT NULL,
|
||||
"plan" text NOT NULL,
|
||||
"amount_cents" numeric(24, 7),
|
||||
"currency" text DEFAULT 'USD' NOT NULL,
|
||||
"cadence" text DEFAULT 'month' NOT NULL,
|
||||
"status" text DEFAULT 'active' NOT NULL,
|
||||
"source" text NOT NULL,
|
||||
"source_url" text,
|
||||
"effective_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
CONSTRAINT "ai_subscription_prices_valid" CHECK (("ai_subscription_prices"."amount_cents" is null or "ai_subscription_prices"."amount_cents" >= 0) and "ai_subscription_prices"."cadence" in ('month','year') and "ai_subscription_prices"."status" in ('active','ended','excluded') and "ai_subscription_prices"."source" in ('catalog','user','unknown'))
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE IF NOT EXISTS "ai_subscriptions" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"company_id" uuid NOT NULL,
|
||||
"provider" text NOT NULL,
|
||||
"account_key" text NOT NULL,
|
||||
"identity_verified" boolean DEFAULT false NOT NULL,
|
||||
"name" text NOT NULL,
|
||||
"owner_user_ids" text[] DEFAULT '{}'::text[] NOT NULL,
|
||||
"shared" boolean DEFAULT false NOT NULL,
|
||||
"detected_plan" text,
|
||||
"observed_at" timestamp with time zone,
|
||||
"last_checked_at" timestamp with time zone,
|
||||
"refresh_status" text,
|
||||
"merged_into_id" uuid,
|
||||
"revision" integer DEFAULT 0 NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
CONSTRAINT "ai_subscriptions_no_self_merge" CHECK ("ai_subscriptions"."merged_into_id" is null or "ai_subscriptions"."merged_into_id" <> "ai_subscriptions"."id")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "cost_events" ADD COLUMN IF NOT EXISTS "subscription_id" uuid;--> statement-breakpoint
|
||||
DO $$ BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'ai_subscription_connections_company_id_companies_id_fk' AND conrelid = 'ai_subscription_connections'::regclass) THEN
|
||||
ALTER TABLE "ai_subscription_connections" ADD CONSTRAINT "ai_subscription_connections_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "public"."companies"("id") ON DELETE cascade ON UPDATE no action;
|
||||
END IF;
|
||||
END $$;--> statement-breakpoint
|
||||
DO $$ BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'ai_subscription_connections_connection_id_tool_connections_id_fk' AND conrelid = 'ai_subscription_connections'::regclass) THEN
|
||||
ALTER TABLE "ai_subscription_connections" ADD CONSTRAINT "ai_subscription_connections_connection_id_tool_connections_id_fk" FOREIGN KEY ("connection_id") REFERENCES "public"."tool_connections"("id") ON DELETE cascade ON UPDATE no action;
|
||||
END IF;
|
||||
END $$;--> statement-breakpoint
|
||||
DO $$ BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'ai_subscription_connections_grant_id_connection_grants_id_fk' AND conrelid = 'ai_subscription_connections'::regclass) THEN
|
||||
ALTER TABLE "ai_subscription_connections" ADD CONSTRAINT "ai_subscription_connections_grant_id_connection_grants_id_fk" FOREIGN KEY ("grant_id") REFERENCES "public"."connection_grants"("id") ON DELETE cascade ON UPDATE no action;
|
||||
END IF;
|
||||
END $$;--> statement-breakpoint
|
||||
DO $$ BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'ai_subscription_connections_subscription_id_ai_subscriptions_id_fk' AND conrelid = 'ai_subscription_connections'::regclass) THEN
|
||||
ALTER TABLE "ai_subscription_connections" ADD CONSTRAINT "ai_subscription_connections_subscription_id_ai_subscriptions_id_fk" FOREIGN KEY ("subscription_id") REFERENCES "public"."ai_subscriptions"("id") ON DELETE cascade ON UPDATE no action;
|
||||
END IF;
|
||||
END $$;--> statement-breakpoint
|
||||
DO $$ BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'ai_subscription_prices_company_id_companies_id_fk' AND conrelid = 'ai_subscription_prices'::regclass) THEN
|
||||
ALTER TABLE "ai_subscription_prices" ADD CONSTRAINT "ai_subscription_prices_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "public"."companies"("id") ON DELETE cascade ON UPDATE no action;
|
||||
END IF;
|
||||
END $$;--> statement-breakpoint
|
||||
DO $$ BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'ai_subscription_prices_subscription_id_ai_subscriptions_id_fk' AND conrelid = 'ai_subscription_prices'::regclass) THEN
|
||||
ALTER TABLE "ai_subscription_prices" ADD CONSTRAINT "ai_subscription_prices_subscription_id_ai_subscriptions_id_fk" FOREIGN KEY ("subscription_id") REFERENCES "public"."ai_subscriptions"("id") ON DELETE cascade ON UPDATE no action;
|
||||
END IF;
|
||||
END $$;--> statement-breakpoint
|
||||
DO $$ BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'ai_subscriptions_company_id_companies_id_fk' AND conrelid = 'ai_subscriptions'::regclass) THEN
|
||||
ALTER TABLE "ai_subscriptions" ADD CONSTRAINT "ai_subscriptions_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "public"."companies"("id") ON DELETE cascade ON UPDATE no action;
|
||||
END IF;
|
||||
END $$;--> statement-breakpoint
|
||||
DO $$ BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'ai_subscriptions_merged_into_id_ai_subscriptions_id_fk' AND conrelid = 'ai_subscriptions'::regclass) THEN
|
||||
ALTER TABLE "ai_subscriptions" ADD CONSTRAINT "ai_subscriptions_merged_into_id_ai_subscriptions_id_fk" FOREIGN KEY ("merged_into_id") REFERENCES "public"."ai_subscriptions"("id") ON DELETE no action ON UPDATE no action;
|
||||
END IF;
|
||||
END $$;--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "ai_subscription_connections_grant_idx" ON "ai_subscription_connections" USING btree ("company_id","grant_id");--> statement-breakpoint
|
||||
CREATE INDEX IF NOT EXISTS "ai_subscription_connections_credential_idx" ON "ai_subscription_connections" USING btree ("company_id","credential_key");--> statement-breakpoint
|
||||
CREATE INDEX IF NOT EXISTS "ai_subscription_connections_account_idx" ON "ai_subscription_connections" USING btree ("company_id","subscription_id");--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "ai_subscription_prices_revision_idx" ON "ai_subscription_prices" USING btree ("subscription_id","revision");--> statement-breakpoint
|
||||
CREATE INDEX IF NOT EXISTS "ai_subscription_prices_company_idx" ON "ai_subscription_prices" USING btree ("company_id");--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "ai_subscriptions_identity_idx" ON "ai_subscriptions" USING btree ("company_id","provider","account_key");--> statement-breakpoint
|
||||
CREATE INDEX IF NOT EXISTS "ai_subscriptions_company_idx" ON "ai_subscriptions" USING btree ("company_id");--> statement-breakpoint
|
||||
DO $$ BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'cost_events_subscription_id_ai_subscriptions_id_fk' AND conrelid = 'cost_events'::regclass) THEN
|
||||
ALTER TABLE "cost_events" ADD CONSTRAINT "cost_events_subscription_id_ai_subscriptions_id_fk" FOREIGN KEY ("subscription_id") REFERENCES "public"."ai_subscriptions"("id") ON DELETE no action ON UPDATE no action;
|
||||
END IF;
|
||||
END $$;--> statement-breakpoint
|
||||
CREATE INDEX IF NOT EXISTS "cost_events_company_subscription_occurred_idx" ON "cost_events" USING btree ("company_id","subscription_id","occurred_at");
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
-55416
File diff suppressed because it is too large.
Load diff
+765
-3
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"id": "d8438290-9b05-4959-ab7f-2097cfdd6ce3",
|
||||
"prevId": "2242ec8f-2d13-46d2-99ed-cf97a52466d2",
|
||||
"id": "677c8c43-8767-4e2b-9cc4-35a76061e6df",
|
||||
"prevId": "3a76c99a-51c4-41d7-b7e2-12b55d8c7d08",
|
||||
"version": "7",
|
||||
"dialect": "postgresql",
|
||||
"tables": {
|
||||
@@ -3914,6 +3914,45 @@
|
||||
"notNull": true,
|
||||
"default": "'idle'"
|
||||
},
|
||||
"lifecycle_state": {
|
||||
"name": "lifecycle_state",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "'ready'"
|
||||
},
|
||||
"lifecycle_required_plugin_ids": {
|
||||
"name": "lifecycle_required_plugin_ids",
|
||||
"type": "jsonb",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"lifecycle_holds": {
|
||||
"name": "lifecycle_holds",
|
||||
"type": "jsonb",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "'[]'::jsonb"
|
||||
},
|
||||
"lifecycle_version": {
|
||||
"name": "lifecycle_version",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": 0
|
||||
},
|
||||
"lifecycle_error": {
|
||||
"name": "lifecycle_error",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"lifecycle_operation": {
|
||||
"name": "lifecycle_operation",
|
||||
"type": "jsonb",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"reports_to": {
|
||||
"name": "reports_to",
|
||||
"type": "uuid",
|
||||
@@ -4026,6 +4065,33 @@
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"agents_lifecycle_work_idx": {
|
||||
"name": "agents_lifecycle_work_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "lifecycle_state",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "updated_at",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
},
|
||||
"agents_company_status_idx": {
|
||||
"name": "agents_company_status_idx",
|
||||
"columns": [
|
||||
@@ -4744,6 +4810,516 @@
|
||||
},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.ai_subscription_connections": {
|
||||
"name": "ai_subscription_connections",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "uuid",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"default": "gen_random_uuid()"
|
||||
},
|
||||
"company_id": {
|
||||
"name": "company_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"connection_id": {
|
||||
"name": "connection_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"grant_id": {
|
||||
"name": "grant_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"credential_key": {
|
||||
"name": "credential_key",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"subscription_id": {
|
||||
"name": "subscription_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"ai_subscription_connections_grant_idx": {
|
||||
"name": "ai_subscription_connections_grant_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "company_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "grant_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": true,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
},
|
||||
"ai_subscription_connections_credential_idx": {
|
||||
"name": "ai_subscription_connections_credential_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "company_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "credential_key",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
},
|
||||
"ai_subscription_connections_account_idx": {
|
||||
"name": "ai_subscription_connections_account_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "company_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "subscription_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
}
|
||||
},
|
||||
"foreignKeys": {
|
||||
"ai_subscription_connections_company_id_companies_id_fk": {
|
||||
"name": "ai_subscription_connections_company_id_companies_id_fk",
|
||||
"tableFrom": "ai_subscription_connections",
|
||||
"tableTo": "companies",
|
||||
"columnsFrom": [
|
||||
"company_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
"ai_subscription_connections_connection_id_tool_connections_id_fk": {
|
||||
"name": "ai_subscription_connections_connection_id_tool_connections_id_fk",
|
||||
"tableFrom": "ai_subscription_connections",
|
||||
"tableTo": "tool_connections",
|
||||
"columnsFrom": [
|
||||
"connection_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
"ai_subscription_connections_grant_id_connection_grants_id_fk": {
|
||||
"name": "ai_subscription_connections_grant_id_connection_grants_id_fk",
|
||||
"tableFrom": "ai_subscription_connections",
|
||||
"tableTo": "connection_grants",
|
||||
"columnsFrom": [
|
||||
"grant_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
"ai_subscription_connections_subscription_id_ai_subscriptions_id_fk": {
|
||||
"name": "ai_subscription_connections_subscription_id_ai_subscriptions_id_fk",
|
||||
"tableFrom": "ai_subscription_connections",
|
||||
"tableTo": "ai_subscriptions",
|
||||
"columnsFrom": [
|
||||
"subscription_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.ai_subscription_prices": {
|
||||
"name": "ai_subscription_prices",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "uuid",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"default": "gen_random_uuid()"
|
||||
},
|
||||
"company_id": {
|
||||
"name": "company_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"subscription_id": {
|
||||
"name": "subscription_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"revision": {
|
||||
"name": "revision",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"plan": {
|
||||
"name": "plan",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"amount_cents": {
|
||||
"name": "amount_cents",
|
||||
"type": "numeric(24, 7)",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"currency": {
|
||||
"name": "currency",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "'USD'"
|
||||
},
|
||||
"cadence": {
|
||||
"name": "cadence",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "'month'"
|
||||
},
|
||||
"status": {
|
||||
"name": "status",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "'active'"
|
||||
},
|
||||
"source": {
|
||||
"name": "source",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"source_url": {
|
||||
"name": "source_url",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"effective_at": {
|
||||
"name": "effective_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"ai_subscription_prices_revision_idx": {
|
||||
"name": "ai_subscription_prices_revision_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "subscription_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "revision",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": true,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
},
|
||||
"ai_subscription_prices_company_idx": {
|
||||
"name": "ai_subscription_prices_company_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "company_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
}
|
||||
},
|
||||
"foreignKeys": {
|
||||
"ai_subscription_prices_company_id_companies_id_fk": {
|
||||
"name": "ai_subscription_prices_company_id_companies_id_fk",
|
||||
"tableFrom": "ai_subscription_prices",
|
||||
"tableTo": "companies",
|
||||
"columnsFrom": [
|
||||
"company_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
"ai_subscription_prices_subscription_id_ai_subscriptions_id_fk": {
|
||||
"name": "ai_subscription_prices_subscription_id_ai_subscriptions_id_fk",
|
||||
"tableFrom": "ai_subscription_prices",
|
||||
"tableTo": "ai_subscriptions",
|
||||
"columnsFrom": [
|
||||
"subscription_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {
|
||||
"ai_subscription_prices_valid": {
|
||||
"name": "ai_subscription_prices_valid",
|
||||
"value": "(\"ai_subscription_prices\".\"amount_cents\" is null or \"ai_subscription_prices\".\"amount_cents\" >= 0) and \"ai_subscription_prices\".\"cadence\" in ('month','year') and \"ai_subscription_prices\".\"status\" in ('active','ended','excluded') and \"ai_subscription_prices\".\"source\" in ('catalog','user','unknown')"
|
||||
}
|
||||
},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.ai_subscriptions": {
|
||||
"name": "ai_subscriptions",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "uuid",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"default": "gen_random_uuid()"
|
||||
},
|
||||
"company_id": {
|
||||
"name": "company_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"provider": {
|
||||
"name": "provider",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"account_key": {
|
||||
"name": "account_key",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"identity_verified": {
|
||||
"name": "identity_verified",
|
||||
"type": "boolean",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": false
|
||||
},
|
||||
"name": {
|
||||
"name": "name",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"owner_user_ids": {
|
||||
"name": "owner_user_ids",
|
||||
"type": "text[]",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "'{}'::text[]"
|
||||
},
|
||||
"shared": {
|
||||
"name": "shared",
|
||||
"type": "boolean",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": false
|
||||
},
|
||||
"detected_plan": {
|
||||
"name": "detected_plan",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"observed_at": {
|
||||
"name": "observed_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"last_checked_at": {
|
||||
"name": "last_checked_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"refresh_status": {
|
||||
"name": "refresh_status",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"merged_into_id": {
|
||||
"name": "merged_into_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"revision": {
|
||||
"name": "revision",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": 0
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"ai_subscriptions_identity_idx": {
|
||||
"name": "ai_subscriptions_identity_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "company_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "provider",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "account_key",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": true,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
},
|
||||
"ai_subscriptions_company_idx": {
|
||||
"name": "ai_subscriptions_company_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "company_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
}
|
||||
},
|
||||
"foreignKeys": {
|
||||
"ai_subscriptions_company_id_companies_id_fk": {
|
||||
"name": "ai_subscriptions_company_id_companies_id_fk",
|
||||
"tableFrom": "ai_subscriptions",
|
||||
"tableTo": "companies",
|
||||
"columnsFrom": [
|
||||
"company_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
"ai_subscriptions_merged_into_id_ai_subscriptions_id_fk": {
|
||||
"name": "ai_subscriptions_merged_into_id_ai_subscriptions_id_fk",
|
||||
"tableFrom": "ai_subscriptions",
|
||||
"tableTo": "ai_subscriptions",
|
||||
"columnsFrom": [
|
||||
"merged_into_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "no action",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {
|
||||
"ai_subscriptions_no_self_merge": {
|
||||
"name": "ai_subscriptions_no_self_merge",
|
||||
"value": "\"ai_subscriptions\".\"merged_into_id\" is null or \"ai_subscriptions\".\"merged_into_id\" <> \"ai_subscriptions\".\"id\""
|
||||
}
|
||||
},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.announcement_dismissals": {
|
||||
"name": "announcement_dismissals",
|
||||
"schema": "",
|
||||
@@ -9480,6 +10056,13 @@
|
||||
"notNull": true,
|
||||
"default": true
|
||||
},
|
||||
"require_at_mention": {
|
||||
"name": "require_at_mention",
|
||||
"type": "boolean",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": false
|
||||
},
|
||||
"allow_group_chats": {
|
||||
"name": "allow_group_chats",
|
||||
"type": "boolean",
|
||||
@@ -11776,6 +12359,139 @@
|
||||
},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.chat_slack_registrations": {
|
||||
"name": "chat_slack_registrations",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"endpoint_id": {
|
||||
"name": "endpoint_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": true,
|
||||
"notNull": true
|
||||
},
|
||||
"company_id": {
|
||||
"name": "company_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"request_id": {
|
||||
"name": "request_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"status": {
|
||||
"name": "status",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"manifest": {
|
||||
"name": "manifest",
|
||||
"type": "jsonb",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"manifest_hash": {
|
||||
"name": "manifest_hash",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"callback_uri": {
|
||||
"name": "callback_uri",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"app_id": {
|
||||
"name": "app_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"client_id": {
|
||||
"name": "client_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"secret_ids": {
|
||||
"name": "secret_ids",
|
||||
"type": "jsonb",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "'{}'::jsonb"
|
||||
},
|
||||
"workspace_id": {
|
||||
"name": "workspace_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"bot_user_id": {
|
||||
"name": "bot_user_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"error_code": {
|
||||
"name": "error_code",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"created_by_user_id": {
|
||||
"name": "created_by_user_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
},
|
||||
"updated_at": {
|
||||
"name": "updated_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {
|
||||
"chat_slack_registrations_company_id_endpoint_id_chat_endpoints_company_id_id_fk": {
|
||||
"name": "chat_slack_registrations_company_id_endpoint_id_chat_endpoints_company_id_id_fk",
|
||||
"tableFrom": "chat_slack_registrations",
|
||||
"tableTo": "chat_endpoints",
|
||||
"columnsFrom": [
|
||||
"company_id",
|
||||
"endpoint_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"company_id",
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {
|
||||
"chat_slack_registration_status_check": {
|
||||
"name": "chat_slack_registration_status_check",
|
||||
"value": "\"chat_slack_registrations\".\"status\" in ('creating', 'uncertain', 'failed', 'install', 'credentials_saved', 'configured', 'removed')"
|
||||
}
|
||||
},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.chat_teams_file_transfers": {
|
||||
"name": "chat_teams_file_transfers",
|
||||
"schema": "",
|
||||
@@ -17354,6 +18070,12 @@
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"subscription_id": {
|
||||
"name": "subscription_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"billing_code": {
|
||||
"name": "billing_code",
|
||||
"type": "text",
|
||||
@@ -17589,6 +18311,33 @@
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
},
|
||||
"cost_events_company_subscription_occurred_idx": {
|
||||
"name": "cost_events_company_subscription_occurred_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "company_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "subscription_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "occurred_at",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
},
|
||||
"cost_events_company_agent_occurred_idx": {
|
||||
"name": "cost_events_company_agent_occurred_idx",
|
||||
"columns": [
|
||||
@@ -17770,6 +18519,19 @@
|
||||
],
|
||||
"onDelete": "no action",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
"cost_events_subscription_id_ai_subscriptions_id_fk": {
|
||||
"name": "cost_events_subscription_id_ai_subscriptions_id_fk",
|
||||
"tableFrom": "cost_events",
|
||||
"tableTo": "ai_subscriptions",
|
||||
"columnsFrom": [
|
||||
"subscription_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "no action",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
@@ -56121,7 +56883,7 @@
|
||||
"name": "expires_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
"notNull": false
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
+558
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"id": "7b6b177a-6067-4d7b-bc90-0300919e490b",
|
||||
"prevId": "3a76c99a-51c4-41d7-b7e2-12b55d8c7d08",
|
||||
"id": "675883cf-dc12-4e9e-a191-a405a4b09788",
|
||||
"prevId": "677c8c43-8767-4e2b-9cc4-35a76061e6df",
|
||||
"version": "7",
|
||||
"dialect": "postgresql",
|
||||
"tables": {
|
||||
@@ -4810,6 +4810,516 @@
|
||||
},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.ai_subscription_connections": {
|
||||
"name": "ai_subscription_connections",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "uuid",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"default": "gen_random_uuid()"
|
||||
},
|
||||
"company_id": {
|
||||
"name": "company_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"connection_id": {
|
||||
"name": "connection_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"grant_id": {
|
||||
"name": "grant_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"credential_key": {
|
||||
"name": "credential_key",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"subscription_id": {
|
||||
"name": "subscription_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"ai_subscription_connections_grant_idx": {
|
||||
"name": "ai_subscription_connections_grant_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "company_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "grant_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": true,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
},
|
||||
"ai_subscription_connections_credential_idx": {
|
||||
"name": "ai_subscription_connections_credential_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "company_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "credential_key",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
},
|
||||
"ai_subscription_connections_account_idx": {
|
||||
"name": "ai_subscription_connections_account_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "company_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "subscription_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
}
|
||||
},
|
||||
"foreignKeys": {
|
||||
"ai_subscription_connections_company_id_companies_id_fk": {
|
||||
"name": "ai_subscription_connections_company_id_companies_id_fk",
|
||||
"tableFrom": "ai_subscription_connections",
|
||||
"tableTo": "companies",
|
||||
"columnsFrom": [
|
||||
"company_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
"ai_subscription_connections_connection_id_tool_connections_id_fk": {
|
||||
"name": "ai_subscription_connections_connection_id_tool_connections_id_fk",
|
||||
"tableFrom": "ai_subscription_connections",
|
||||
"tableTo": "tool_connections",
|
||||
"columnsFrom": [
|
||||
"connection_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
"ai_subscription_connections_grant_id_connection_grants_id_fk": {
|
||||
"name": "ai_subscription_connections_grant_id_connection_grants_id_fk",
|
||||
"tableFrom": "ai_subscription_connections",
|
||||
"tableTo": "connection_grants",
|
||||
"columnsFrom": [
|
||||
"grant_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
"ai_subscription_connections_subscription_id_ai_subscriptions_id_fk": {
|
||||
"name": "ai_subscription_connections_subscription_id_ai_subscriptions_id_fk",
|
||||
"tableFrom": "ai_subscription_connections",
|
||||
"tableTo": "ai_subscriptions",
|
||||
"columnsFrom": [
|
||||
"subscription_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.ai_subscription_prices": {
|
||||
"name": "ai_subscription_prices",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "uuid",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"default": "gen_random_uuid()"
|
||||
},
|
||||
"company_id": {
|
||||
"name": "company_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"subscription_id": {
|
||||
"name": "subscription_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"revision": {
|
||||
"name": "revision",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"plan": {
|
||||
"name": "plan",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"amount_cents": {
|
||||
"name": "amount_cents",
|
||||
"type": "numeric(24, 7)",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"currency": {
|
||||
"name": "currency",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "'USD'"
|
||||
},
|
||||
"cadence": {
|
||||
"name": "cadence",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "'month'"
|
||||
},
|
||||
"status": {
|
||||
"name": "status",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "'active'"
|
||||
},
|
||||
"source": {
|
||||
"name": "source",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"source_url": {
|
||||
"name": "source_url",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"effective_at": {
|
||||
"name": "effective_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"ai_subscription_prices_revision_idx": {
|
||||
"name": "ai_subscription_prices_revision_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "subscription_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "revision",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": true,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
},
|
||||
"ai_subscription_prices_company_idx": {
|
||||
"name": "ai_subscription_prices_company_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "company_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
}
|
||||
},
|
||||
"foreignKeys": {
|
||||
"ai_subscription_prices_company_id_companies_id_fk": {
|
||||
"name": "ai_subscription_prices_company_id_companies_id_fk",
|
||||
"tableFrom": "ai_subscription_prices",
|
||||
"tableTo": "companies",
|
||||
"columnsFrom": [
|
||||
"company_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
"ai_subscription_prices_subscription_id_ai_subscriptions_id_fk": {
|
||||
"name": "ai_subscription_prices_subscription_id_ai_subscriptions_id_fk",
|
||||
"tableFrom": "ai_subscription_prices",
|
||||
"tableTo": "ai_subscriptions",
|
||||
"columnsFrom": [
|
||||
"subscription_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {
|
||||
"ai_subscription_prices_valid": {
|
||||
"name": "ai_subscription_prices_valid",
|
||||
"value": "(\"ai_subscription_prices\".\"amount_cents\" is null or \"ai_subscription_prices\".\"amount_cents\" >= 0) and \"ai_subscription_prices\".\"cadence\" in ('month','year') and \"ai_subscription_prices\".\"status\" in ('active','ended','excluded') and \"ai_subscription_prices\".\"source\" in ('catalog','user','unknown')"
|
||||
}
|
||||
},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.ai_subscriptions": {
|
||||
"name": "ai_subscriptions",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "uuid",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"default": "gen_random_uuid()"
|
||||
},
|
||||
"company_id": {
|
||||
"name": "company_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"provider": {
|
||||
"name": "provider",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"account_key": {
|
||||
"name": "account_key",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"identity_verified": {
|
||||
"name": "identity_verified",
|
||||
"type": "boolean",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": false
|
||||
},
|
||||
"name": {
|
||||
"name": "name",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"owner_user_ids": {
|
||||
"name": "owner_user_ids",
|
||||
"type": "text[]",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "'{}'::text[]"
|
||||
},
|
||||
"shared": {
|
||||
"name": "shared",
|
||||
"type": "boolean",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": false
|
||||
},
|
||||
"detected_plan": {
|
||||
"name": "detected_plan",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"observed_at": {
|
||||
"name": "observed_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"last_checked_at": {
|
||||
"name": "last_checked_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"refresh_status": {
|
||||
"name": "refresh_status",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"merged_into_id": {
|
||||
"name": "merged_into_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"revision": {
|
||||
"name": "revision",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": 0
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"ai_subscriptions_identity_idx": {
|
||||
"name": "ai_subscriptions_identity_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "company_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "provider",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "account_key",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": true,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
},
|
||||
"ai_subscriptions_company_idx": {
|
||||
"name": "ai_subscriptions_company_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "company_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
}
|
||||
},
|
||||
"foreignKeys": {
|
||||
"ai_subscriptions_company_id_companies_id_fk": {
|
||||
"name": "ai_subscriptions_company_id_companies_id_fk",
|
||||
"tableFrom": "ai_subscriptions",
|
||||
"tableTo": "companies",
|
||||
"columnsFrom": [
|
||||
"company_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
"ai_subscriptions_merged_into_id_ai_subscriptions_id_fk": {
|
||||
"name": "ai_subscriptions_merged_into_id_ai_subscriptions_id_fk",
|
||||
"tableFrom": "ai_subscriptions",
|
||||
"tableTo": "ai_subscriptions",
|
||||
"columnsFrom": [
|
||||
"merged_into_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "no action",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {
|
||||
"ai_subscriptions_no_self_merge": {
|
||||
"name": "ai_subscriptions_no_self_merge",
|
||||
"value": "\"ai_subscriptions\".\"merged_into_id\" is null or \"ai_subscriptions\".\"merged_into_id\" <> \"ai_subscriptions\".\"id\""
|
||||
}
|
||||
},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.announcement_dismissals": {
|
||||
"name": "announcement_dismissals",
|
||||
"schema": "",
|
||||
@@ -18821,6 +19331,12 @@
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"subscription_id": {
|
||||
"name": "subscription_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"billing_code": {
|
||||
"name": "billing_code",
|
||||
"type": "text",
|
||||
@@ -19056,6 +19572,33 @@
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
},
|
||||
"cost_events_company_subscription_occurred_idx": {
|
||||
"name": "cost_events_company_subscription_occurred_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "company_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "subscription_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "occurred_at",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
},
|
||||
"cost_events_company_agent_occurred_idx": {
|
||||
"name": "cost_events_company_agent_occurred_idx",
|
||||
"columns": [
|
||||
@@ -19237,6 +19780,19 @@
|
||||
],
|
||||
"onDelete": "no action",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
"cost_events_subscription_id_ai_subscriptions_id_fk": {
|
||||
"name": "cost_events_subscription_id_ai_subscriptions_id_fk",
|
||||
"tableFrom": "cost_events",
|
||||
"tableTo": "ai_subscriptions",
|
||||
"columnsFrom": [
|
||||
"subscription_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "no action",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
+21
-14
@@ -2245,50 +2245,57 @@
|
||||
{
|
||||
"idx": 322,
|
||||
"version": "7",
|
||||
"when": 1791568503478,
|
||||
"tag": "0322_long_franklin_storm",
|
||||
"when": 1791572660423,
|
||||
"tag": "0322_reflective_kree",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 323,
|
||||
"version": "7",
|
||||
"when": 1791568503479,
|
||||
"tag": "0323_aberrant_machine_man",
|
||||
"when": 1791572660424,
|
||||
"tag": "0323_long_franklin_storm",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 324,
|
||||
"version": "7",
|
||||
"when": 1791568503480,
|
||||
"tag": "0324_blushing_screwball",
|
||||
"when": 1791572660425,
|
||||
"tag": "0324_aberrant_machine_man",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 325,
|
||||
"version": "7",
|
||||
"when": 1791568503481,
|
||||
"tag": "0325_sad_proteus",
|
||||
"when": 1791572660426,
|
||||
"tag": "0325_blushing_screwball",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 326,
|
||||
"version": "7",
|
||||
"when": 1791568503482,
|
||||
"tag": "0326_chunky_mentallo",
|
||||
"when": 1791572660427,
|
||||
"tag": "0326_sad_proteus",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 327,
|
||||
"version": "7",
|
||||
"when": 1791568503483,
|
||||
"tag": "0327_free_wolf_cub",
|
||||
"when": 1791572660428,
|
||||
"tag": "0327_chunky_mentallo",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 328,
|
||||
"version": "7",
|
||||
"when": 1791568503484,
|
||||
"tag": "0328_spooky_white_tiger",
|
||||
"when": 1791572660429,
|
||||
"tag": "0328_free_wolf_cub",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 329,
|
||||
"version": "7",
|
||||
"when": 1791572660430,
|
||||
"tag": "0329_spooky_white_tiger",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { sql } from "drizzle-orm";
|
||||
import { pgTable, uuid, text, timestamp, boolean, integer, numeric, index, uniqueIndex, check, type AnyPgColumn } from "drizzle-orm/pg-core";
|
||||
import { companies } from "./companies.js";
|
||||
import { connectionGrants, toolConnections } from "./tool_access.js";
|
||||
|
||||
/** An estimate of a recurring account fee, deliberately separate from receipts. */
|
||||
export const aiSubscriptions = pgTable("ai_subscriptions", {
|
||||
id: uuid("id").primaryKey().defaultRandom(),
|
||||
companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),
|
||||
provider: text("provider").notNull(),
|
||||
// Company-scoped digest of provider account AND seat, or an unverified credential.
|
||||
accountKey: text("account_key").notNull(),
|
||||
identityVerified: boolean("identity_verified").notNull().default(false),
|
||||
name: text("name").notNull(),
|
||||
// A paid seat can be connected personally and shared. Retain all billing
|
||||
// editors even after a connection is deleted; disconnecting is not cancellation.
|
||||
ownerUserIds: text("owner_user_ids").array().notNull().default(sql`'{}'::text[]`),
|
||||
shared: boolean("shared").notNull().default(false),
|
||||
detectedPlan: text("detected_plan"),
|
||||
observedAt: timestamp("observed_at", { withTimezone: true }),
|
||||
lastCheckedAt: timestamp("last_checked_at", { withTimezone: true }),
|
||||
refreshStatus: text("refresh_status").$type<"ok" | "unavailable">(),
|
||||
mergedIntoId: uuid("merged_into_id").references((): AnyPgColumn => aiSubscriptions.id),
|
||||
revision: integer("revision").notNull().default(0),
|
||||
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
}, table => ({
|
||||
identity: uniqueIndex("ai_subscriptions_identity_idx").on(table.companyId, table.provider, table.accountKey),
|
||||
company: index("ai_subscriptions_company_idx").on(table.companyId),
|
||||
noSelfMerge: check("ai_subscriptions_no_self_merge", sql`${table.mergedIntoId} is null or ${table.mergedIntoId} <> ${table.id}`),
|
||||
}));
|
||||
|
||||
export const aiSubscriptionPrices = pgTable("ai_subscription_prices", {
|
||||
id: uuid("id").primaryKey().defaultRandom(),
|
||||
companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),
|
||||
subscriptionId: uuid("subscription_id").notNull().references(() => aiSubscriptions.id, { onDelete: "cascade" }),
|
||||
revision: integer("revision").notNull(),
|
||||
plan: text("plan").notNull(),
|
||||
amountCents: numeric("amount_cents", { precision: 24, scale: 7 }),
|
||||
currency: text("currency").notNull().default("USD"),
|
||||
cadence: text("cadence").$type<"month" | "year">().notNull().default("month"),
|
||||
status: text("status").$type<"active" | "ended" | "excluded">().notNull().default("active"),
|
||||
source: text("source").$type<"catalog" | "user" | "unknown">().notNull(),
|
||||
sourceUrl: text("source_url"),
|
||||
effectiveAt: timestamp("effective_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
}, table => ({
|
||||
version: uniqueIndex("ai_subscription_prices_revision_idx").on(table.subscriptionId, table.revision),
|
||||
company: index("ai_subscription_prices_company_idx").on(table.companyId),
|
||||
valid: check("ai_subscription_prices_valid", sql`(${table.amountCents} is null or ${table.amountCents} >= 0) and ${table.cadence} in ('month','year') and ${table.status} in ('active','ended','excluded') and ${table.source} in ('catalog','user','unknown')`),
|
||||
}));
|
||||
|
||||
/** Current credential-to-account binding. Runs snapshot the subscription ID. */
|
||||
export const aiSubscriptionConnections = pgTable("ai_subscription_connections", {
|
||||
id: uuid("id").primaryKey().defaultRandom(),
|
||||
companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),
|
||||
connectionId: uuid("connection_id").notNull().references(() => toolConnections.id, { onDelete: "cascade" }),
|
||||
grantId: uuid("grant_id").notNull().references(() => connectionGrants.id, { onDelete: "cascade" }),
|
||||
credentialKey: text("credential_key").notNull(),
|
||||
subscriptionId: uuid("subscription_id").notNull().references(() => aiSubscriptions.id, { onDelete: "cascade" }),
|
||||
}, table => ({
|
||||
grant: uniqueIndex("ai_subscription_connections_grant_idx").on(table.companyId, table.grantId),
|
||||
credential: index("ai_subscription_connections_credential_idx").on(table.companyId, table.credentialKey),
|
||||
account: index("ai_subscription_connections_account_idx").on(table.companyId, table.subscriptionId),
|
||||
}));
|
||||
@@ -6,6 +6,7 @@ import { issues } from "./issues.js";
|
||||
import { projects } from "./projects.js";
|
||||
import { goals } from "./goals.js";
|
||||
import { heartbeatRuns } from "./heartbeat_runs.js";
|
||||
import { aiSubscriptions } from "./ai_subscriptions.js";
|
||||
|
||||
export const costEvents = pgTable(
|
||||
"cost_events",
|
||||
@@ -19,6 +20,7 @@ export const costEvents = pgTable(
|
||||
projectId: uuid("project_id").references(() => projects.id),
|
||||
goalId: uuid("goal_id").references(() => goals.id),
|
||||
heartbeatRunId: uuid("heartbeat_run_id").references(() => heartbeatRuns.id),
|
||||
subscriptionId: uuid("subscription_id").references(() => aiSubscriptions.id),
|
||||
billingCode: text("billing_code"),
|
||||
idempotencyKey: text("idempotency_key"),
|
||||
receiptHash: text("receipt_hash"),
|
||||
@@ -45,6 +47,7 @@ export const costEvents = pgTable(
|
||||
companyProjectOccurredIdx: index("cost_events_company_project_occurred_idx").on(table.companyId, table.projectId, table.occurredAt),
|
||||
unpricedIdx: index("cost_events_unpriced_idx").on(table.companyId, table.occurredAt, table.id).where(sql`${table.costStatus} = 'unpriced' and ${table.billingType} <> 'subscription_included'`),
|
||||
companyOccurredIdx: index("cost_events_company_occurred_idx").on(table.companyId, table.occurredAt),
|
||||
companySubscriptionOccurredIdx: index("cost_events_company_subscription_occurred_idx").on(table.companyId, table.subscriptionId, table.occurredAt),
|
||||
companyAgentOccurredIdx: index("cost_events_company_agent_occurred_idx").on(
|
||||
table.companyId,
|
||||
table.agentId,
|
||||
|
||||
@@ -243,3 +243,4 @@ export { chatVoiceReports } from "./chat_voice_reports.js";
|
||||
export { chatVoicePhoneLines, chatVoiceInboundCalls } from "./chat_voice_inbound.js";
|
||||
export * from "./decision_models.js";
|
||||
export { userCompanyPreferences } from "./user_company_preferences.js";
|
||||
export { aiSubscriptions, aiSubscriptionPrices, aiSubscriptionConnections } from "./ai_subscriptions.js";
|
||||
@@ -30,7 +30,7 @@ const support = await getEmbeddedPostgresTestSupport();
|
||||
await sql.unsafe(`ALTER TABLE ${table} DROP CONSTRAINT ${name}`);
|
||||
await sql.unsafe(`ALTER TABLE ${table} ADD CONSTRAINT ${name} CHECK (${definition})`);
|
||||
}
|
||||
for (const name of ["0322_long_franklin_storm.sql", "0323_aberrant_machine_man.sql", "0324_blushing_screwball.sql", "0325_sad_proteus.sql", "0326_chunky_mentallo.sql", "0327_free_wolf_cub.sql", "0328_spooky_white_tiger.sql"]) {
|
||||
for (const name of ["0323_long_franklin_storm.sql", "0324_aberrant_machine_man.sql", "0325_blushing_screwball.sql", "0326_sad_proteus.sql", "0327_chunky_mentallo.sql", "0328_free_wolf_cub.sql", "0329_spooky_white_tiger.sql"]) {
|
||||
const migration = await readFile(new URL(`./migrations/${name}`, import.meta.url), "utf8");
|
||||
const hash = createHash("sha256").update(migration).digest("hex");
|
||||
await sql`DELETE FROM drizzle.__drizzle_migrations WHERE hash = ${hash}`;
|
||||
@@ -71,7 +71,7 @@ const support = await getEmbeddedPostgresTestSupport();
|
||||
await applyPendingMigrations(database.connectionString);
|
||||
// Existing installations have older migration hashes after renumbering.
|
||||
// Force each stage to execute again while preserving the actual saved rows.
|
||||
for (const name of ["0322_long_franklin_storm.sql", "0323_aberrant_machine_man.sql", "0324_blushing_screwball.sql", "0325_sad_proteus.sql", "0326_chunky_mentallo.sql", "0327_free_wolf_cub.sql", "0328_spooky_white_tiger.sql"]) {
|
||||
for (const name of ["0323_long_franklin_storm.sql", "0324_aberrant_machine_man.sql", "0325_blushing_screwball.sql", "0326_sad_proteus.sql", "0327_chunky_mentallo.sql", "0328_free_wolf_cub.sql", "0329_spooky_white_tiger.sql"]) {
|
||||
const migration = await readFile(new URL(`./migrations/${name}`, import.meta.url), "utf8");
|
||||
const hash = createHash("sha256").update(migration).digest("hex");
|
||||
await sql`DELETE FROM drizzle.__drizzle_migrations WHERE hash = ${hash}`;
|
||||
|
||||
@@ -144,6 +144,8 @@ export type AiConnectionUnavailableReason =
|
||||
| "access_denied"
|
||||
| "credential_missing";
|
||||
export interface AiConnectionAttribution {
|
||||
/** Billing account at execution time; never resolved again from mutable settings. */
|
||||
subscriptionId?: string;
|
||||
connectionId: string;
|
||||
grantId: string;
|
||||
provider: AiProvider;
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import type { AgentLifecycleState } from "./types/agent-lifecycle.js";
|
||||
|
||||
/** JSON responses for the operator-owned Dot invitation flow. Pairing capabilities are transient. */
|
||||
export interface DotBinding {
|
||||
id: string;
|
||||
@@ -17,6 +19,8 @@ export interface DotConnection {
|
||||
enabled: boolean;
|
||||
resourceUrl: string | null;
|
||||
agentStatus: string;
|
||||
agentLifecycleState: AgentLifecycleState;
|
||||
canConfigureConnection: boolean;
|
||||
binding: DotBinding | null;
|
||||
}
|
||||
export interface DotPairing { bindingId: string; pairingCode: string; expiresAt: string }
|
||||
@@ -2811,6 +2811,7 @@ export * from "./agent-appearance.js";
|
||||
export * from "./ai-connections.js";
|
||||
export * from "./ai-connection-router.js";
|
||||
export * from "./ai-connection-usage.js";
|
||||
export * from "./subscriptions.js";
|
||||
export * from "./types/email.js";
|
||||
export * from "./validators/email.js";
|
||||
export { configureRailwaySshSchema, type ConfigureRailwaySsh, type RailwaySshSetup } from "./railway-connection.js";
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
import { z } from "zod";
|
||||
import { exactCentsSchema } from "./accounting.js";
|
||||
import { centsToUnits, unitsToCents } from "./money.js";
|
||||
|
||||
export const SUBSCRIPTION_CURRENCIES = ["USD", "EUR", "GBP", "CAD", "AUD", "CHF"] as const;
|
||||
export const subscriptionPriceSchema = z.object({
|
||||
expectedRevision: z.number().int().nonnegative(),
|
||||
plan: z.string().trim().min(1).max(100),
|
||||
amountCents: exactCentsSchema.nullable(),
|
||||
currency: z.enum(SUBSCRIPTION_CURRENCIES),
|
||||
cadence: z.enum(["month", "year"]),
|
||||
status: z.enum(["active", "ended", "excluded"]),
|
||||
}).strict();
|
||||
export type UpdateSubscriptionPrice = z.input<typeof subscriptionPriceSchema>;
|
||||
export const mergeSubscriptionsSchema = z.object({
|
||||
targetId: z.string().uuid(),
|
||||
expectedRevision: z.number().int().nonnegative(),
|
||||
targetRevision: z.number().int().nonnegative(),
|
||||
}).strict();
|
||||
|
||||
export interface SubscriptionPlan {
|
||||
id: string;
|
||||
provider: string;
|
||||
name: string;
|
||||
monthlyCents: string;
|
||||
currency: "USD";
|
||||
sourceUrl: string;
|
||||
checkedAt: string;
|
||||
}
|
||||
|
||||
// Web list prices, before tax, assuming monthly billing. These are estimates,
|
||||
// never invoices. Generic Pro/Max/team entitlements do not identify a price.
|
||||
export const SUBSCRIPTION_PLANS: readonly SubscriptionPlan[] = [
|
||||
["openai", "free", "ChatGPT Free", "0", "https://learn.chatgpt.com/docs/pricing"],
|
||||
["openai", "go", "ChatGPT Go", "800", "https://learn.chatgpt.com/docs/pricing"],
|
||||
["openai", "plus", "ChatGPT Plus", "2000", "https://learn.chatgpt.com/docs/pricing"],
|
||||
["anthropic", "pro", "Claude Pro", "2000", "https://claude.com/pricing"],
|
||||
["anthropic", "max_5x", "Claude Max 5x", "10000", "https://claude.com/pricing"],
|
||||
["anthropic", "max_20x", "Claude Max 20x", "20000", "https://claude.com/pricing"],
|
||||
["xai", "supergrok", "SuperGrok", "3000", "https://x.ai/pricing"],
|
||||
["xai", "supergrok_plus", "SuperGrok Plus", "10000", "https://x.ai/pricing"],
|
||||
].map(([provider, id, name, monthlyCents, sourceUrl]) => ({
|
||||
provider, id, name, monthlyCents, sourceUrl, currency: "USD", checkedAt: "2026-10-08",
|
||||
}));
|
||||
|
||||
export function subscriptionPlan(provider: string, plan: string | null): SubscriptionPlan | null {
|
||||
const key = plan?.trim().toLowerCase().replaceAll(" ", "_");
|
||||
return SUBSCRIPTION_PLANS.find(item => item.provider === provider && item.id === key) ?? null;
|
||||
}
|
||||
|
||||
export function monthlySubscriptionCents(amount: string, cadence: "month" | "year"): string {
|
||||
const units = centsToUnits(amount);
|
||||
return unitsToCents(cadence === "year" ? (units + 6n) / 12n : units);
|
||||
}
|
||||
|
||||
export interface SubscriptionPrice {
|
||||
revision: number;
|
||||
plan: string;
|
||||
amountCents: string | null;
|
||||
monthlyCents: string | null;
|
||||
currency: string;
|
||||
cadence: "month" | "year";
|
||||
status: "active" | "ended" | "excluded";
|
||||
source: "catalog" | "user" | "unknown";
|
||||
sourceUrl: string | null;
|
||||
effectiveAt: string;
|
||||
}
|
||||
|
||||
export interface SubscriptionUsage {
|
||||
inputTokens: number;
|
||||
cachedInputTokens: number;
|
||||
outputTokens: number;
|
||||
costCents: string;
|
||||
eventCount: number;
|
||||
estimatedEventCount: number;
|
||||
unpricedEventCount: number;
|
||||
}
|
||||
|
||||
export interface SubscriptionAccountReport {
|
||||
id: string;
|
||||
provider: string;
|
||||
name: string;
|
||||
ownerUserId: string | null;
|
||||
ownerName: string | null;
|
||||
shared: boolean;
|
||||
identityVerified: boolean;
|
||||
detectedPlan: string | null;
|
||||
observedAt: string | null;
|
||||
lastCheckedAt: string | null;
|
||||
refreshStatus: "ok" | "unavailable" | null;
|
||||
canEdit: boolean;
|
||||
price: SubscriptionPrice;
|
||||
usage: SubscriptionUsage;
|
||||
agents: { id: string; name: string }[];
|
||||
}
|
||||
|
||||
export interface SubscriptionCostReport {
|
||||
canRefresh: boolean;
|
||||
/** Current monthly commitment for accounts visible to the caller;
|
||||
* independent of the usage date filter. Aggregate run usage is company-wide. */
|
||||
asOf: string;
|
||||
accounts: SubscriptionAccountReport[];
|
||||
monthlyTotals: { currency: string; amountCents: string; estimatedCount: number }[];
|
||||
activeCount: number;
|
||||
unknownPriceCount: number;
|
||||
unidentifiedAccountCount: number;
|
||||
api: SubscriptionUsage;
|
||||
subscription: SubscriptionUsage;
|
||||
/** Other billing types (credits, fixed, or unknown), outside API/subscription totals. */
|
||||
unknown: SubscriptionUsage;
|
||||
unattributedSubscription: SubscriptionUsage;
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import type { AgentAppearance } from "../agent-appearance.js";
|
||||
import type { BillingType, CostStatus } from "../constants.js";
|
||||
|
||||
export interface CostEvent {
|
||||
subscriptionId?: string | null;
|
||||
usageKind?: "agent" | "decision";
|
||||
responsibleUserId?: string | null;
|
||||
id: string;
|
||||
@@ -174,6 +175,9 @@ export interface CostWindowSpendRow {
|
||||
export interface CostByProject {
|
||||
projectId: string | null;
|
||||
projectName: string | null;
|
||||
/** Ledger events in this project and selected date range, not distinct runs. */
|
||||
eventCount: number;
|
||||
estimatedEventCount: number;
|
||||
costCents: number;
|
||||
costCentsExact?: string;
|
||||
inputTokens: number;
|
||||
|
||||
@@ -2,6 +2,9 @@ import { connectionIntentService } from "../services/connection-intents.js";
|
||||
import { connectionIntentDeliveryService } from "../services/connection-intent-delivery.js";
|
||||
import { issueRecoveryActionService } from "../services/issue-recovery-actions.js";
|
||||
import { localAiLoginService } from "../services/local-ai-login.js";
|
||||
// Background plan observations have their own provider-fixture coverage. Runtime
|
||||
// auth tests must not send the selected fixture credentials to a real provider.
|
||||
vi.mock("../services/subscription-refresh.js", () => ({ refreshSubscriptionConnection: vi.fn().mockResolvedValue(undefined) }));
|
||||
import * as localCredentials from "../services/local-ai-credentials.js";
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
@@ -1407,6 +1410,9 @@ console.log(JSON.stringify({ type: "result", subtype: "success", result: "hello"
|
||||
try {
|
||||
expect(child.identity).toBe(parent.identity);
|
||||
expect(child.attribution.grantId).toBe(account.grantId);
|
||||
expect(parent.attribution.subscriptionId).toEqual(expect.any(String));
|
||||
expect(child.attribution.subscriptionId).toBe(parent.attribution.subscriptionId);
|
||||
expect(child.config.managedAiConnection).toMatchObject({ subscriptionId: parent.attribution.subscriptionId });
|
||||
} finally {
|
||||
await Promise.all([parent.cleanup(), child.cleanup()]);
|
||||
}
|
||||
|
||||
@@ -537,6 +537,7 @@ describeEmbeddedPostgres("cost and finance aggregate overflow handling", () => {
|
||||
cachedInputTokens: 10,
|
||||
outputTokens: 200_000_000,
|
||||
costCents: 2_000_000_000,
|
||||
costStatus: "estimated",
|
||||
occurredAt: new Date("2026-04-11T00:00:00.000Z"),
|
||||
},
|
||||
]);
|
||||
@@ -555,6 +556,11 @@ describeEmbeddedPostgres("cost and finance aggregate overflow handling", () => {
|
||||
expect(byAgentRow?.inputTokens).toBe(3_999_999_990);
|
||||
expect(byAgentRow!.inputTokens + byAgentRow!.cachedInputTokens).toBe(4_000_000_000);
|
||||
expect(byProjectRow?.costCents).toBe(4_000_000_000);
|
||||
expect(byProjectRow).toMatchObject({ eventCount: 2, estimatedEventCount: 1 });
|
||||
const [firstDayProject] = await costs.byProject(companyId, {
|
||||
...range, to: new Date("2026-04-10T23:59:59.999Z"),
|
||||
});
|
||||
expect(firstDayProject).toMatchObject({ eventCount: 1, estimatedEventCount: 0 });
|
||||
expect(byAgentModelRow?.costCents).toBe(4_000_000_000);
|
||||
});
|
||||
|
||||
|
||||
@@ -128,3 +128,31 @@ it("does not trust editable agent metadata as an invitation ownership receipt",
|
||||
expect(await service.resume(f.companyId, f.userId)).toBeNull();
|
||||
expect((await service.create(f.companyId, f.userId)).agent.id).not.toBe(spoof!.id);
|
||||
});
|
||||
|
||||
it("reports connection setup authority separately from compatibility status", async () => {
|
||||
const f = await fixture();
|
||||
const invite = await dotInvitationService(db).create(f.companyId, f.userId);
|
||||
const app = express();
|
||||
app.use((req, _res, next) => {
|
||||
req.actor = { type: "board", source: "session", userId: f.userId, companyIds: [f.companyId],
|
||||
memberships: [{ companyId: f.companyId, membershipRole: "owner", status: "active" }] };
|
||||
next();
|
||||
});
|
||||
app.use(dotRunnerRoutes(db, "https://paperclip.example/mcp/runner"));
|
||||
const path = `/companies/${f.companyId}/agents/${invite.agent.id}/dot-binding`;
|
||||
const cases = [
|
||||
{ lifecycleState: "preparing", status: "paused", allowed: true },
|
||||
{ lifecycleState: "verifying", status: "paused", allowed: true },
|
||||
{ lifecycleState: "ready", status: "idle", allowed: true },
|
||||
{ lifecycleState: "paused", status: "paused", allowed: false },
|
||||
{ lifecycleState: "pending_approval", status: "pending_approval", allowed: false },
|
||||
{ lifecycleState: "terminated", status: "terminated", allowed: false },
|
||||
] as const;
|
||||
for (const state of cases) {
|
||||
await db.update(agents).set({ lifecycleState: state.lifecycleState, status: state.status }).where(eq(agents.id, invite.agent.id));
|
||||
const result = await request(app).get(path);
|
||||
expect(result.status).toBe(200);
|
||||
expect(result.body).toMatchObject({ agentStatus: state.status, agentLifecycleState: state.lifecycleState,
|
||||
canConfigureConnection: state.allowed });
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,81 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { refreshCompanySubscriptions, refreshSubscriptionConnection } from "../services/subscription-refresh.js";
|
||||
import type { SubscriptionConnection } from "../services/subscriptions.js";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ accounts: vi.fn(), credential: vi.fn(), register: vi.fn(), probe: vi.fn() }));
|
||||
vi.mock("../services/ai-connections.js", () => ({ aiConnectionService: () => ({ subscriptionAccounts: mocks.accounts, credential: mocks.credential }) }));
|
||||
vi.mock("../services/subscriptions.js", () => ({ subscriptionService: () => ({ register: mocks.register }) }));
|
||||
vi.mock("../services/subscription-identity.js", () => ({ probeSubscriptionIdentity: mocks.probe }));
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
const promise = new Promise<T>(done => { resolve = done; });
|
||||
return { promise, resolve };
|
||||
}
|
||||
function database() {
|
||||
return {
|
||||
update: () => ({ set: () => ({ where: () => ({ returning: async () => [{ id: "claimed" }] }) }) }),
|
||||
select: () => ({ from: () => ({ where: async () => [{ credentialKey: "fixture-key" }] }) }),
|
||||
} as unknown as Db;
|
||||
}
|
||||
const input = (id: string): SubscriptionConnection => ({ companyId: id, connectionId: id, grantId: id, provider: "openai", name: id, ownerUserId: "alice", credential: "fixture" });
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
mocks.credential.mockResolvedValue("fixture");
|
||||
mocks.register.mockImplementation(async (connection: SubscriptionConnection) => connection.grantId);
|
||||
});
|
||||
|
||||
describe("subscription discovery capacity", () => {
|
||||
it.each([false, true])("waits for a provider slot without dropping accepted discovery (provider fails: %s)", async (fails) => {
|
||||
const db = database();
|
||||
const gates = Array.from({ length: 5 }, () => deferred<void>());
|
||||
let started = 0, active = 0, peak = 0;
|
||||
mocks.probe.mockImplementation(async () => {
|
||||
const index = started++;
|
||||
peak = Math.max(peak, ++active);
|
||||
await gates[index].promise;
|
||||
active--;
|
||||
if (index === 0 && fails) throw new Error("fixture provider failure");
|
||||
return { credentialKey: "fixture-key" };
|
||||
});
|
||||
mocks.accounts.mockResolvedValue([{ summary: { status: "connected", provider: "openai" },
|
||||
connection: { id: "fifth", name: "Fifth account" }, grant: { id: "fifth", subjectUserId: "alice" } }]);
|
||||
const running = Array.from({ length: 4 }, (_, i) => refreshSubscriptionConnection(db, input(`busy-${i}`), `busy-${i}`));
|
||||
let discovery: Promise<void> | undefined;
|
||||
try {
|
||||
await vi.waitFor(() => expect(started).toBe(4));
|
||||
let completed = false;
|
||||
discovery = refreshCompanySubscriptions(db, "fifth", "alice").then(() => { completed = true; });
|
||||
await vi.waitFor(() => expect(mocks.register).toHaveBeenCalledWith(expect.objectContaining({ grantId: "fifth" })));
|
||||
expect(started).toBe(4);
|
||||
expect(completed).toBe(false);
|
||||
gates[0].resolve();
|
||||
await vi.waitFor(() => expect(started).toBe(5));
|
||||
expect(peak).toBe(4);
|
||||
gates[4].resolve();
|
||||
await discovery;
|
||||
expect(mocks.register).toHaveBeenCalledWith(expect.objectContaining({ grantId: "fifth" }), { credentialKey: "fixture-key" });
|
||||
} finally {
|
||||
gates.forEach(gate => gate.resolve());
|
||||
await Promise.all([...running, discovery]);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects excess discovery with a retryable error, deduplicates accepted work, and releases capacity", async () => {
|
||||
const db = database(), gate = deferred<[]>();
|
||||
mocks.accounts.mockReturnValue(gate.promise);
|
||||
const accepted = Array.from({ length: 20 }, (_, i) => refreshCompanySubscriptions(db, "company", `user-${i}`));
|
||||
try {
|
||||
expect(refreshCompanySubscriptions(db, "company", "user-0")).toBe(accepted[0]);
|
||||
expect(mocks.accounts).toHaveBeenCalledTimes(20);
|
||||
expect(() => refreshCompanySubscriptions(db, "company", "overflow")).toThrow(expect.objectContaining({ status: 429 }));
|
||||
} finally {
|
||||
gate.resolve([]);
|
||||
await Promise.all(accepted);
|
||||
}
|
||||
await refreshCompanySubscriptions(db, "company", "overflow");
|
||||
expect(mocks.accounts).toHaveBeenCalledTimes(21);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
import express from "express";
|
||||
import request from "supertest";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { costRoutes } from "../routes/costs.js";
|
||||
import { errorHandler } from "../middleware/error-handler.js";
|
||||
import { tooManyRequests } from "../errors.js";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ report: vi.fn(), refresh: vi.fn(), updatePrice: vi.fn(), merge: vi.fn(), decide: vi.fn() }));
|
||||
vi.mock("../services/subscription-report.js", () => ({ subscriptionCostReport: mocks.report }));
|
||||
vi.mock("../services/subscription-refresh.js", () => ({ refreshCompanySubscriptions: mocks.refresh }));
|
||||
vi.mock("../services/subscriptions.js", () => ({ subscriptionService: () => mocks }));
|
||||
vi.mock("../routes/ai-connections.js", () => ({ canManageAiConnections: async () => false }));
|
||||
vi.mock("../services/index.js", () => ({
|
||||
heartbeatService: () => ({}), costService: () => ({}), financeService: () => ({}), budgetService: () => ({}),
|
||||
companyService: () => ({}), agentService: () => ({}), issueService: () => ({}), accessService: () => ({ decide: mocks.decide }),
|
||||
}));
|
||||
vi.mock("../services/accounting-integrity.js", () => ({ accountingIntegrityService: () => ({}) }));
|
||||
vi.mock("../services/billing-reconciliation.js", () => ({ billingReconciliationService: () => ({}) }));
|
||||
|
||||
const companyId = "11111111-1111-4111-8111-111111111111";
|
||||
const accountId = "22222222-2222-4222-8222-222222222222";
|
||||
function app(type: "board" | "agent" = "board", role = "member") {
|
||||
const app = express(); app.use(express.json());
|
||||
app.use((req, _res, next) => { req.actor = type === "board" ? { type: "board", source: "session", userId: "alice", companyIds: [companyId], memberships: [{ companyId, status: "active", membershipRole: role }] } as typeof req.actor : { type: "agent", agentId: "agent", companyId } as typeof req.actor; next(); });
|
||||
app.use("/api", costRoutes({} as Db)); app.use(errorHandler); return app;
|
||||
}
|
||||
beforeEach(() => { vi.clearAllMocks(); mocks.decide.mockResolvedValue({ allowed: true }); mocks.report.mockResolvedValue({ accounts: [] }); mocks.refresh.mockResolvedValue(undefined); mocks.updatePrice.mockResolvedValue({ id: accountId }); });
|
||||
describe("subscription reporting authorization", () => {
|
||||
it("allows company cost reads but rejects agents, other companies and invalid dates", async () => {
|
||||
const path = `/api/companies/${companyId}/costs/subscriptions`;
|
||||
expect((await request(app()).get(path)).status).toBe(200);
|
||||
expect((await request(app("agent")).get(path)).status).toBe(403);
|
||||
expect((await request(app()).get("/api/companies/other/costs/subscriptions")).status).toBe(403);
|
||||
expect((await request(app()).get(`${path}?from=not-a-date`)).status).toBe(400);
|
||||
expect((await request(app()).get(`${path}?period=all`)).status).toBe(200);
|
||||
expect(mocks.report).toHaveBeenLastCalledWith(expect.anything(), companyId, expect.anything(), { allTime: true });
|
||||
mocks.decide.mockResolvedValue({ allowed: false });
|
||||
expect((await request(app()).get(path)).status).toBe(403);
|
||||
});
|
||||
it("returns immediately while authorized discovery runs and denies viewers", async () => {
|
||||
mocks.refresh.mockReturnValue(new Promise(() => {}));
|
||||
const path = `/api/companies/${companyId}/costs/subscriptions/refresh`;
|
||||
expect((await request(app()).post(path)).status).toBe(202);
|
||||
expect(mocks.refresh).toHaveBeenCalledWith(expect.anything(), companyId, "alice");
|
||||
expect((await request(app("board", "viewer")).post(path)).status).toBe(403);
|
||||
});
|
||||
it("validates edits and passes ownership and optimistic concurrency to the service", async () => {
|
||||
const path = `/api/companies/${companyId}/costs/subscriptions/${accountId}`;
|
||||
const data = { expectedRevision: 3, plan: "Pro", amountCents: "2000", currency: "USD", cadence: "month", status: "active" };
|
||||
expect((await request(app()).patch(path).send(data)).status).toBe(200);
|
||||
expect(mocks.updatePrice).toHaveBeenCalledWith(companyId, accountId, expect.objectContaining({ expectedRevision: 3, amountCents: "2000.0000000" }), { userId: "alice", canManage: false, readOnly: false });
|
||||
expect((await request(app()).patch(path).send({ ...data, amountCents: "-1" })).status).toBe(400);
|
||||
expect((await request(app()).patch(path).send({ ...data, ownerUserId: "bob" })).status).toBe(400);
|
||||
expect((await request(app("agent")).patch(path).send(data)).status).toBe(403);
|
||||
mocks.decide.mockResolvedValue({ allowed: false });
|
||||
expect((await request(app()).patch(path).send(data)).status).toBe(403);
|
||||
expect((await request(app()).post(`${path}/link`).send({ targetId: accountId, expectedRevision: 3, targetRevision: 3 })).status).toBe(403);
|
||||
});
|
||||
it("returns a retryable error instead of accepting discovery beyond capacity", async () => {
|
||||
mocks.refresh.mockImplementationOnce(() => { throw tooManyRequests("Subscription account checks are busy. Try again shortly."); });
|
||||
const response = await request(app()).post(`/api/companies/${companyId}/costs/subscriptions/refresh`);
|
||||
expect(response.status).toBe(429);
|
||||
expect(response.body.error).toContain("Try again shortly");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,492 @@
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { and, eq, sql } from "drizzle-orm";
|
||||
import { createDb, companies, agents, heartbeatRuns, costEvents, activityLog, aiSubscriptions, aiSubscriptionPrices, aiSubscriptionConnections, toolApplications, toolConnections, connectionGrants, connectionGrantMembers } from "@paperclipai/db";
|
||||
import { startEmbeddedPostgresTestDatabase } from "@paperclipai/db/test-embedded-postgres";
|
||||
import { monthlySubscriptionCents, subscriptionPlan, subscriptionPriceSchema } from "@paperclipai/shared";
|
||||
import { subscriptionService, type SubscriptionConnection } from "../services/subscriptions.js";
|
||||
import { subscriptionCostReport } from "../services/subscription-report.js";
|
||||
import { refreshSubscriptionConnection } from "../services/subscription-refresh.js";
|
||||
import { subscriptionCredentialIdentity, probeSubscriptionIdentity } from "../services/subscription-identity.js";
|
||||
import { costService } from "../services/costs.js";
|
||||
import { toolAccessService } from "../services/tool-access.js";
|
||||
import * as liveEvents from "../services/live-events.js";
|
||||
|
||||
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
||||
let db: ReturnType<typeof createDb>;
|
||||
const owner = { userId: "alice", canManage: false };
|
||||
const other = { userId: "bob", canManage: true };
|
||||
const jwt = (body: unknown) => `header.${Buffer.from(JSON.stringify(body)).toString("base64url")}.signature`;
|
||||
const token = (workspace = "workspace", seat = "alice", plan = "plus", generation = "1") => JSON.stringify({ tokens: {
|
||||
account_id: workspace, access_token: jwt({ sub: seat, generation,
|
||||
"https://api.openai.com/auth": { chatgpt_account_id: workspace, chatgpt_user_id: seat } }),
|
||||
id_token: jwt({ sub: seat, "https://api.openai.com/auth": { chatgpt_plan_type: plan, chatgpt_user_id: seat } }),
|
||||
} });
|
||||
const fixtureRequest = (body: unknown) => vi.fn<typeof fetch>().mockImplementation(async () => Response.json(body));
|
||||
const usage = (plan = "plus") => ({ plan_type: plan, rate_limit: { primary_window: { used_percent: 1, reset_at: 1800000000, limit_window_seconds: 18000 } } });
|
||||
async function verifiedConnection(input: SubscriptionConnection) {
|
||||
const observed = await probeSubscriptionIdentity(input.companyId, input.provider, input.credential, fixtureRequest(usage()));
|
||||
return subscriptionService(db).register(input, observed);
|
||||
}
|
||||
|
||||
beforeAll(async () => { database = await startEmbeddedPostgresTestDatabase("paperclip-subscriptions-"); db = createDb(database.connectionString); }, 90000);
|
||||
afterAll(async () => { await database?.cleanup(); });
|
||||
|
||||
async function company() {
|
||||
const id = randomUUID();
|
||||
await db.insert(companies).values({ id, name: "Subscription fixture", issuePrefix: `S${id.replaceAll("-", "").slice(0, 7).toUpperCase()}` });
|
||||
return id;
|
||||
}
|
||||
async function connection(companyId: string, credential = token(), provider: SubscriptionConnection["provider"] = "openai", userId: string | null = "alice") {
|
||||
const applicationId = randomUUID(), connectionId = randomUUID(), grantId = randomUUID();
|
||||
await db.insert(toolApplications).values({ id: applicationId, companyId, name: applicationId, type: "custom" });
|
||||
await db.insert(toolConnections).values({ id: connectionId, companyId, applicationId, name: "My subscription", uid: connectionId,
|
||||
connectionPurpose: "ai", transport: "runtime_auth", status: "active", enabled: true, config: { ai: { provider, method: "subscription" } } });
|
||||
await db.insert(connectionGrants).values({ id: grantId, companyId, connectionId, kind: userId ? "user" : "organization", subjectUserId: userId });
|
||||
return { companyId, connectionId, grantId, credential, provider, name: "My subscription", ownerUserId: userId };
|
||||
}
|
||||
async function price(companyId: string, id: string, amountCents: string | null = "10000", extra: Record<string, unknown> = {}, actor = owner) {
|
||||
const [account] = await db.select().from(aiSubscriptions).where(eq(aiSubscriptions.id, id));
|
||||
return subscriptionService(db).updatePrice(companyId, id, { expectedRevision: account.revision, plan: "My plan", amountCents, currency: "USD", cadence: "month", status: "active", ...extra }, actor);
|
||||
}
|
||||
async function event(companyId: string, subscriptionId: string | null, billingType: "metered_api" | "subscription_included" | "subscription_overage" | "credits" | "fixed" | "unknown", amount = "0", occurredAt = new Date("2026-10-08T00:00:00Z")) {
|
||||
const agentId = randomUUID();
|
||||
await db.insert(agents).values({ id: agentId, companyId, name: "Agent", role: "engineer", adapterType: "codex_local" });
|
||||
await db.insert(costEvents).values({ companyId, agentId, subscriptionId, provider: "openai", biller: "openai", billingType, model: "fixture",
|
||||
costCents: Number(amount), inputTokens: 100, cachedInputTokens: 40, outputTokens: 10, receiptHash: "normalized", occurredAt });
|
||||
return agentId;
|
||||
}
|
||||
|
||||
describe("subscription identity and price rules", () => {
|
||||
it("requires provider authentication, a seat and a workspace, and never persists a credential or email", async () => {
|
||||
const observed = (companyId: string, credential: string) => probeSubscriptionIdentity(companyId, "openai", credential, fixtureRequest(usage()));
|
||||
const a = await observed("company", token());
|
||||
expect(a.verified).toBe(true);
|
||||
expect(a.accountKey).toBe((await observed("company", token("workspace", "alice", "plus", "2"))).accountKey);
|
||||
expect(a.accountKey).not.toBe((await observed("company", token("workspace", "bob"))).accountKey);
|
||||
expect(a.accountKey).not.toBe((await observed("other-company", token())).accountKey);
|
||||
expect(JSON.stringify(a)).not.toMatch(/workspace|alice|access-1|signature/);
|
||||
expect(subscriptionCredentialIdentity("company", "openai", token()).verified).toBe(false);
|
||||
expect(subscriptionCredentialIdentity("company", "openai", '{"tokens":{"account_id":"workspace"}}').verified).toBe(false);
|
||||
await expect(probeSubscriptionIdentity("company", "openai", token(), async () => new Response(null, { status: 401 }))).rejects.toThrow();
|
||||
const opaque = JSON.parse(token()); opaque.tokens.access_token = "opaque-bearer";
|
||||
expect((await observed("company", JSON.stringify(opaque))).verified).toBe(false);
|
||||
const wrongWorkspace = JSON.parse(token()); wrongWorkspace.tokens.account_id = "another-workspace";
|
||||
expect((await observed("company", JSON.stringify(wrongWorkspace))).verified).toBe(false);
|
||||
});
|
||||
it("keeps ambiguous tiers unknown and uses exact monthly equivalents", () => {
|
||||
expect(subscriptionPlan("openai", "pro")).toBeNull();
|
||||
expect(subscriptionPlan("anthropic", "max")).toBeNull();
|
||||
expect(subscriptionPlan("openai", "business")).toBeNull();
|
||||
expect(subscriptionPlan("openai", "unrecognized")).toBeNull();
|
||||
expect(monthlySubscriptionCents("20000", "year")).toBe("1666.6666667");
|
||||
expect(monthlySubscriptionCents("1", "year")).toBe("0.0833333");
|
||||
expect(monthlySubscriptionCents("0", "month")).toBe("0.0000000");
|
||||
expect(subscriptionPriceSchema.safeParse({ expectedRevision: 0, plan: "Max", amountCents: "-1", currency: "USD", cadence: "month", status: "active" }).success).toBe(false);
|
||||
});
|
||||
it("uses a Claude account and organization profile, never infers a Max tier from token usage", async () => {
|
||||
const request = fixtureRequest({ account: { uuid: "person" }, organization: { uuid: "org", organization_type: "claude_max", rate_limit_tier: "default_claude_max_20x" } });
|
||||
const observed = await probeSubscriptionIdentity("company", "anthropic", "selected-secret", request);
|
||||
expect(observed.plan).toBe("max_20x");
|
||||
expect(observed.verified).toBe(true);
|
||||
expect(JSON.stringify(observed)).not.toContain("selected-secret");
|
||||
expect(request).toHaveBeenCalledWith("https://api.anthropic.com/api/oauth/profile", expect.objectContaining({ redirect: "error", headers: expect.objectContaining({ Authorization: "Bearer selected-secret" }) }));
|
||||
await expect(probeSubscriptionIdentity("company", "anthropic", "selected-secret", fixtureRequest({}))).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("durable subscription reporting", () => {
|
||||
it("can replay the migration and retains fees after connection deletion", async () => {
|
||||
const migration = await readFile(new URL("../../../packages/db/src/migrations/0322_reflective_kree.sql", import.meta.url), "utf8");
|
||||
for (const statement of migration.split("--> statement-breakpoint")) await db.execute(sql.raw(statement));
|
||||
const c = await company(), input = await connection(c);
|
||||
await verifiedConnection(input);
|
||||
await db.delete(connectionGrants).where(eq(connectionGrants.id, input.grantId));
|
||||
await db.delete(toolConnections).where(eq(toolConnections.id, input.connectionId));
|
||||
expect(await db.select().from(aiSubscriptionConnections).where(eq(aiSubscriptionConnections.companyId, c))).toHaveLength(0);
|
||||
expect((await subscriptionCostReport(db, c, owner)).monthlyTotals[0].amountCents).toBe("2000.0000000");
|
||||
await db.delete(toolApplications).where(eq(toolApplications.companyId, c));
|
||||
await db.delete(activityLog).where(eq(activityLog.companyId, c));
|
||||
await db.delete(companies).where(eq(companies.id, c));
|
||||
expect(await db.select().from(aiSubscriptions).where(eq(aiSubscriptions.companyId, c))).toHaveLength(0);
|
||||
expect(await db.select().from(aiSubscriptionPrices).where(eq(aiSubscriptionPrices.companyId, c))).toHaveLength(0);
|
||||
});
|
||||
it("rejects a different provider, revoked grant, or foreign company before discovery", async () => {
|
||||
const c = await company(), input = await connection(c), service = subscriptionService(db);
|
||||
await expect(service.register({ ...input, provider: "anthropic" })).rejects.toMatchObject({ status: 404 });
|
||||
await expect(service.register({ ...input, companyId: await company() })).rejects.toMatchObject({ status: 404 });
|
||||
await db.update(connectionGrants).set({ status: "revoked" }).where(eq(connectionGrants.id, input.grantId));
|
||||
await expect(service.register(input)).rejects.toMatchObject({ status: 404 });
|
||||
expect(await db.select().from(aiSubscriptions).where(eq(aiSubscriptions.companyId, c))).toHaveLength(0);
|
||||
});
|
||||
it.each([401, 200])("cannot acquire another owner's billing rights with forged ID claims (provider status %s)", async (status) => {
|
||||
const c = await company(), service = subscriptionService(db);
|
||||
const victim = await verifiedConnection(await connection(c));
|
||||
const forged = JSON.parse(token("workspace", "attacker"));
|
||||
forged.tokens.id_token = JSON.parse(token()).tokens.id_token;
|
||||
const attacker = await connection(c, JSON.stringify(forged), "openai", "bob");
|
||||
const provisional = await service.register(attacker);
|
||||
expect(provisional).not.toBe(victim);
|
||||
await expect(price(c, victim, "0", { status: "excluded" }, other)).rejects.toMatchObject({ status: 403 });
|
||||
await refreshSubscriptionConnection(db, attacker, provisional, status === 200 ? fixtureRequest(usage()) : async () => new Response(null, { status }));
|
||||
await expect(price(c, victim, "0", { status: "excluded" }, other)).rejects.toMatchObject({ status: 403 });
|
||||
const report = await subscriptionCostReport(db, c, other);
|
||||
expect(report.accounts.find(row => row.id === victim)).toBeUndefined();
|
||||
const [account] = await db.select().from(aiSubscriptions).where(eq(aiSubscriptions.id, victim));
|
||||
expect(account.ownerUserIds).toEqual(["alice"]);
|
||||
});
|
||||
it("keeps unverified credentials grant-scoped even when two members submit identical bytes", async () => {
|
||||
const c = await company(), service = subscriptionService(db);
|
||||
const personal = await connection(c, "unverified", "anthropic");
|
||||
const id = await service.register(personal);
|
||||
await price(c, id, "10000");
|
||||
const otherId = await service.register(await connection(c, "unverified", "anthropic", "bob"));
|
||||
expect(otherId).not.toBe(id);
|
||||
await expect(price(c, id, "0", { status: "excluded" }, other)).rejects.toMatchObject({ status: 403 });
|
||||
expect(await service.register(personal)).toBe(id);
|
||||
});
|
||||
it("requires fresh provider proof before an identical credential grants a new personal editor", async () => {
|
||||
const c = await company(), service = subscriptionService(db);
|
||||
const id = await verifiedConnection(await connection(c));
|
||||
const second = await connection(c, token(), "openai", "bob");
|
||||
const provisional = await service.register(second);
|
||||
expect(provisional).not.toBe(id);
|
||||
await refreshSubscriptionConnection(db, second, provisional, async () => new Response(null, { status: 401 }));
|
||||
await expect(price(c, id, "0", { status: "excluded" }, other)).rejects.toMatchObject({ status: 403 });
|
||||
await db.update(aiSubscriptions).set({ lastCheckedAt: new Date(0) }).where(eq(aiSubscriptions.id, provisional));
|
||||
await refreshSubscriptionConnection(db, second, provisional, fixtureRequest(usage()));
|
||||
await price(c, id, "1900", {}, other);
|
||||
await price(c, id, "1800", {}, owner);
|
||||
const report = await subscriptionCostReport(db, c, other);
|
||||
expect(report.accounts).toHaveLength(1);
|
||||
expect(report.monthlyTotals[0].amountCents).toBe("1800.0000000");
|
||||
});
|
||||
it("deduplicates concurrent connections and rotations, while separating seats and companies", async () => {
|
||||
const c = await company(), service = subscriptionService(db);
|
||||
const a = await connection(c), b = await connection(c, token("workspace", "alice", "plus", "rotated"));
|
||||
const [first, second] = await Promise.all([verifiedConnection(a), verifiedConnection(b)]);
|
||||
expect(first).toBe(second);
|
||||
expect(await verifiedConnection(await connection(c, token("workspace", "bob"), "openai", "bob"))).not.toBe(first);
|
||||
expect(await verifiedConnection(await connection(await company()))).not.toBe(first);
|
||||
const report = await subscriptionCostReport(db, c, owner, { allTime: true });
|
||||
expect(report.activeCount).toBe(1);
|
||||
expect(report.monthlyTotals).toEqual([{ currency: "USD", amountCents: "2000.0000000", estimatedCount: 1 }]);
|
||||
expect((await subscriptionCostReport(db, c, other)).activeCount).toBe(1);
|
||||
expect(report.accounts.find(row => row.id === second)?.price.revision).toBe(0);
|
||||
});
|
||||
it("does not multiply automatic fees when a plan has no stable account identity", async () => {
|
||||
const c = await company(), service = subscriptionService(db);
|
||||
const credential = JSON.parse(token());
|
||||
delete credential.tokens.account_id;
|
||||
for (const generation of ["first", "rotated"]) {
|
||||
credential.tokens.access_token = generation;
|
||||
await service.register(await connection(c, JSON.stringify(credential)));
|
||||
}
|
||||
const report = await subscriptionCostReport(db, c, owner);
|
||||
expect(report.monthlyTotals).toEqual([]);
|
||||
expect(report.unknownPriceCount).toBe(2);
|
||||
expect(report.unidentifiedAccountCount).toBe(2);
|
||||
expect(report.accounts.every(account => account.detectedPlan === "plus")).toBe(true);
|
||||
});
|
||||
it("keeps fixed fees through zero-use periods and disconnection; preserves price history and currency", async () => {
|
||||
const c = await company(), input = await connection(c), service = subscriptionService(db);
|
||||
const id = await service.register(input);
|
||||
await price(c, id, "20000", { cadence: "year", currency: "EUR" });
|
||||
await db.update(connectionGrants).set({ status: "revoked" }).where(eq(connectionGrants.id, input.grantId));
|
||||
const report = await subscriptionCostReport(db, c, owner, { from: new Date("2020-01-01"), to: new Date("2020-01-07") });
|
||||
expect(report.monthlyTotals).toEqual([{ currency: "EUR", amountCents: "1666.6666667", estimatedCount: 0 }]);
|
||||
expect(await db.select().from(aiSubscriptionPrices).where(eq(aiSubscriptionPrices.subscriptionId, id))).toHaveLength(2);
|
||||
expect(report.accounts[0]).not.toHaveProperty("history");
|
||||
expect(report.accounts[0].usage.eventCount).toBe(0);
|
||||
expect((await db.select().from(costEvents).where(eq(costEvents.companyId, c)))).toHaveLength(0);
|
||||
const [state] = await db.select().from(companies).where(eq(companies.id, c));
|
||||
expect(state.spentMonthlyCents).toBe(0);
|
||||
await price(c, id, "20000", { status: "ended" });
|
||||
expect((await subscriptionCostReport(db, c, owner)).activeCount).toBe(0);
|
||||
});
|
||||
it("deduplicates profile observations, preserves manual prices, and reuses promoted credentials", async () => {
|
||||
const c = await company(), service = subscriptionService(db);
|
||||
const first = await connection(c, "claude-first", "anthropic");
|
||||
const second = await connection(c, "claude-second", "anthropic");
|
||||
const firstId = await service.register(first), secondId = await service.register(second);
|
||||
await price(c, secondId, "9500");
|
||||
await event(c, firstId, "subscription_included"); await event(c, secondId, "subscription_included");
|
||||
const profile = fixtureRequest({ account: { uuid: "seat" }, organization: { uuid: "workspace", organization_type: "claude_max", rate_limit_tier: "default_claude_max_5x" } });
|
||||
await refreshSubscriptionConnection(db, first, firstId, profile);
|
||||
await refreshSubscriptionConnection(db, second, secondId, profile);
|
||||
const third = await connection(c, "claude-second", "anthropic"), thirdId = await service.register(third);
|
||||
expect(thirdId).not.toBe(firstId);
|
||||
await refreshSubscriptionConnection(db, third, thirdId, profile);
|
||||
expect(await service.register(third)).toBe(firstId);
|
||||
const report = await subscriptionCostReport(db, c, owner, { allTime: true });
|
||||
expect(report.accounts).toHaveLength(1);
|
||||
expect(report.monthlyTotals).toEqual([{ currency: "USD", amountCents: "9500.0000000", estimatedCount: 0 }]);
|
||||
expect(report.accounts[0]).toMatchObject({ identityVerified: true, usage: { eventCount: 2 }, price: { source: "user" } });
|
||||
});
|
||||
it("records detected plan changes without rewriting earlier prices or treating an unknown tier as zero", async () => {
|
||||
const c = await company(), input = await connection(c), id = await verifiedConnection(input);
|
||||
await db.update(aiSubscriptions).set({ lastCheckedAt: new Date(0) }).where(eq(aiSubscriptions.id, id));
|
||||
await refreshSubscriptionConnection(db, input, id, fixtureRequest(usage("pro")));
|
||||
const report = await subscriptionCostReport(db, c, owner);
|
||||
expect((await db.select().from(aiSubscriptionPrices).where(eq(aiSubscriptionPrices.subscriptionId, id)).orderBy(aiSubscriptionPrices.revision)).map(price => price.amountCents)).toEqual(["2000.0000000", null]);
|
||||
expect(report.monthlyTotals).toEqual([]);
|
||||
expect(report.unknownPriceCount).toBe(1);
|
||||
const observedAt = report.accounts[0].observedAt;
|
||||
await db.update(aiSubscriptions).set({ lastCheckedAt: new Date(0) }).where(eq(aiSubscriptions.id, id));
|
||||
await refreshSubscriptionConnection(db, input, id, fixtureRequest({ ...usage(), plan_type: null }));
|
||||
const after = (await subscriptionCostReport(db, c, owner)).accounts[0];
|
||||
expect(after.observedAt).toBe(observedAt);
|
||||
expect(after.detectedPlan).toBe("pro");
|
||||
expect(await db.select().from(aiSubscriptionPrices).where(eq(aiSubscriptionPrices.subscriptionId, id))).toHaveLength(2);
|
||||
expect(after.refreshStatus).toBe("unavailable");
|
||||
});
|
||||
it("keeps shared subscription permissions and currencies separate", async () => {
|
||||
const c = await company(), service = subscriptionService(db);
|
||||
await verifiedConnection(await connection(c));
|
||||
const shared = await service.register(await connection(c, token("shared"), "openai", null));
|
||||
await expect(price(c, shared)).rejects.toMatchObject({ status: 403 });
|
||||
await price(c, shared, "2100", { currency: "EUR" }, other);
|
||||
const report = await subscriptionCostReport(db, c, owner);
|
||||
expect(report.monthlyTotals).toEqual([
|
||||
{ currency: "EUR", amountCents: "2100.0000000", estimatedCount: 0 },
|
||||
{ currency: "USD", amountCents: "2000.0000000", estimatedCount: 1 },
|
||||
]);
|
||||
});
|
||||
it.each([true, false])("preserves personal and shared editors regardless of discovery order (shared first: %s)", async (sharedFirst) => {
|
||||
const c = await company(), service = subscriptionService(db);
|
||||
const personal = await connection(c), shared = await connection(c, token(), "openai", null);
|
||||
const first = await verifiedConnection(sharedFirst ? shared : personal);
|
||||
expect(await verifiedConnection(sharedFirst ? personal : shared)).toBe(first);
|
||||
await price(c, first, "1900", {}, owner);
|
||||
await price(c, first, "1800", {}, other);
|
||||
for (const actor of [owner, other]) {
|
||||
const report = await subscriptionCostReport(db, c, actor);
|
||||
expect(report.accounts).toHaveLength(1);
|
||||
expect(report.accounts[0]).toMatchObject({ canEdit: true, ownerUserId: null });
|
||||
expect(report.monthlyTotals[0].amountCents).toBe("1800.0000000");
|
||||
}
|
||||
await expect(price(c, first, "1700", {}, { ...other, canManage: false })).rejects.toMatchObject({ status: 403 });
|
||||
await expect(price(c, first, "1700", {}, { ...owner, readOnly: true })).rejects.toMatchObject({ status: 403 });
|
||||
// Removing authentication connections must not remove the ability to end
|
||||
// a fee that can still be billed by the provider.
|
||||
await db.delete(connectionGrants).where(eq(connectionGrants.companyId, c));
|
||||
await price(c, first, "1700", {}, owner);
|
||||
await price(c, first, "1700", { status: "ended" }, other);
|
||||
expect((await subscriptionCostReport(db, c, owner)).activeCount).toBe(0);
|
||||
});
|
||||
it.each([true, false])("combines editors when verified profiles link accounts (shared first: %s)", async (sharedFirst) => {
|
||||
const c = await company(), service = subscriptionService(db);
|
||||
const personal = await connection(c, "claude-personal", "anthropic");
|
||||
const shared = await connection(c, "claude-shared", "anthropic", null);
|
||||
const personalId = await service.register(personal), sharedId = await service.register(shared);
|
||||
const profile = fixtureRequest({ account: { uuid: "seat" }, organization: { uuid: "org", rate_limit_tier: "default_claude_max_5x" } });
|
||||
const order = sharedFirst ? [[shared, sharedId], [personal, personalId]] as const : [[personal, personalId], [shared, sharedId]] as const;
|
||||
for (const [input, id] of order) await refreshSubscriptionConnection(db, input, id, profile);
|
||||
const report = await subscriptionCostReport(db, c, owner);
|
||||
expect(report.accounts).toHaveLength(1);
|
||||
const id = report.accounts[0].id;
|
||||
await price(c, id, "9500", {}, owner);
|
||||
await price(c, id, "9000", {}, other);
|
||||
expect((await subscriptionCostReport(db, c, other)).accounts[0].canEdit).toBe(true);
|
||||
expect((await subscriptionCostReport(db, c, owner)).monthlyTotals[0].amountCents).toBe("9000.0000000");
|
||||
});
|
||||
it("retains every personal owner without granting managers access to a personal-only fee", async () => {
|
||||
const c = await company(), service = subscriptionService(db);
|
||||
const id = await verifiedConnection(await connection(c));
|
||||
expect(await verifiedConnection(await connection(c, token(), "openai", "carol"))).toBe(id);
|
||||
await price(c, id, "1800", {}, { userId: "carol", canManage: false });
|
||||
await price(c, id, "1900", {}, owner);
|
||||
await expect(price(c, id, "2000", {}, other)).rejects.toMatchObject({ status: 403 });
|
||||
expect((await subscriptionCostReport(db, c, other)).accounts).toEqual([]);
|
||||
expect((await subscriptionCostReport(db, c, owner)).accounts[0]).toMatchObject({ canEdit: true, shared: false, ownerUserId: null });
|
||||
});
|
||||
it.each([false, true])("keeps another member's personal fees private from cost readers (manager: %s)", async (canManage) => {
|
||||
const c = await company(), input = await connection(c), id = await verifiedConnection(input);
|
||||
await price(c, id, "1234", { plan: "Private negotiated plan" });
|
||||
await event(c, id, "subscription_included");
|
||||
const hidden = await subscriptionCostReport(db, c, { userId: "bob", canManage }, { allTime: true });
|
||||
expect(hidden.accounts).toEqual([]);
|
||||
expect(hidden.monthlyTotals).toEqual([]);
|
||||
expect(hidden.activeCount).toBe(0);
|
||||
expect(hidden.unknownPriceCount).toBe(0);
|
||||
expect(hidden.subscription.eventCount).toBe(1);
|
||||
expect(hidden.unattributedSubscription.eventCount).toBe(0);
|
||||
expect(JSON.stringify(hidden)).not.toMatch(/Private negotiated plan|alice|1234/);
|
||||
const visible = await subscriptionCostReport(db, c, { ...owner, readOnly: true });
|
||||
expect(visible.accounts[0]).toMatchObject({ id, canEdit: false, price: { amountCents: "1234.0000000" } });
|
||||
});
|
||||
it("respects shared connection audiences while retaining managers' access after disconnection", async () => {
|
||||
const c = await company(), input = await connection(c, token(), "openai", null), id = await verifiedConnection(input);
|
||||
await db.insert(connectionGrantMembers).values({ companyId: c, grantId: input.grantId, subjectType: "user", subjectId: "bob" });
|
||||
expect((await subscriptionCostReport(db, c, owner)).accounts).toEqual([]);
|
||||
expect((await subscriptionCostReport(db, c, { ...other, canManage: false })).accounts[0]).toMatchObject({ id, shared: true, canEdit: false });
|
||||
expect((await subscriptionCostReport(db, c, { ...owner, canManage: true })).accounts[0]).toMatchObject({ id, canEdit: true });
|
||||
await db.delete(connectionGrants).where(eq(connectionGrants.id, input.grantId));
|
||||
expect((await subscriptionCostReport(db, c, { ...other, canManage: false })).accounts).toEqual([]);
|
||||
expect((await subscriptionCostReport(db, c, { ...owner, canManage: true })).accounts[0].id).toBe(id);
|
||||
});
|
||||
it.each([false, true])("revokes shared fee visibility through the public revoke service (restricted audience: %s)", async (restricted) => {
|
||||
const c = await company(), input = await connection(c, token(), "openai", null), id = await verifiedConnection(input);
|
||||
expect(await verifiedConnection(await connection(c))).toBe(id);
|
||||
if (restricted) await db.insert(connectionGrantMembers).values({ companyId: c, grantId: input.grantId, subjectType: "user", subjectId: "bob" });
|
||||
await event(c, id, "subscription_included");
|
||||
const reader = { userId: "bob", canManage: false };
|
||||
expect((await subscriptionCostReport(db, c, reader, { allTime: true })).accounts[0]).toMatchObject({ id, usage: { eventCount: 1 } });
|
||||
|
||||
await toolAccessService(db).revokeConnectionGrant(input.connectionId, input.grantId, { actorType: "user", actorId: "alice" });
|
||||
const [grant] = await db.select().from(connectionGrants).where(eq(connectionGrants.id, input.grantId));
|
||||
expect(grant.status).toBe("revoked");
|
||||
expect(await db.select().from(connectionGrantMembers).where(eq(connectionGrantMembers.grantId, input.grantId))).toHaveLength(restricted ? 1 : 0);
|
||||
const hidden = await subscriptionCostReport(db, c, reader, { allTime: true });
|
||||
expect(hidden.accounts).toEqual([]);
|
||||
expect(hidden.monthlyTotals).toEqual([]);
|
||||
expect(hidden.activeCount).toBe(0);
|
||||
expect(hidden.subscription.eventCount).toBe(1);
|
||||
expect(hidden.unattributedSubscription.eventCount).toBe(0);
|
||||
expect(JSON.stringify(hidden)).not.toContain(id);
|
||||
for (const editor of [owner, { userId: "carol", canManage: true }]) {
|
||||
const report = await subscriptionCostReport(db, c, editor);
|
||||
expect(report.accounts[0]).toMatchObject({ id, canEdit: true });
|
||||
expect(report.monthlyTotals[0].amountCents).toBe("2000.0000000");
|
||||
}
|
||||
|
||||
// A different active shared grant can independently authorize the reader.
|
||||
expect(await verifiedConnection(await connection(c, token(), "openai", null))).toBe(id);
|
||||
expect((await subscriptionCostReport(db, c, reader)).accounts[0].id).toBe(id);
|
||||
});
|
||||
it("keeps private linked-account usage out of details without calling it unattributed", async () => {
|
||||
const c = await company(), service = subscriptionService(db);
|
||||
const a = await service.register(await connection(c, "private-a", "anthropic"));
|
||||
const b = await service.register(await connection(c, "private-b", "anthropic"));
|
||||
await event(c, a, "subscription_included"); await event(c, b, "subscription_included");
|
||||
await event(c, null, "subscription_included");
|
||||
await service.merge(c, a, b, 0, 0, owner);
|
||||
const hidden = await subscriptionCostReport(db, c, other, { allTime: true });
|
||||
expect(hidden.accounts).toEqual([]);
|
||||
expect(hidden.subscription.eventCount).toBe(3);
|
||||
expect(hidden.unattributedSubscription.eventCount).toBe(1);
|
||||
expect(JSON.stringify(hidden)).not.toContain(a);
|
||||
expect(JSON.stringify(hidden)).not.toContain(b);
|
||||
});
|
||||
it("reports only current prices while preserving accumulated revisions for auditing", async () => {
|
||||
const c = await company(), service = subscriptionService(db);
|
||||
const id = await service.register(await connection(c));
|
||||
await db.insert(aiSubscriptionPrices).values(Array.from({ length: 500 }, (_, i) => ({
|
||||
companyId: c, subscriptionId: id, revision: i + 1, plan: `Historic plan ${i}`, amountCents: "1000", source: "user" as const,
|
||||
})));
|
||||
await db.update(aiSubscriptions).set({ revision: 500 }).where(eq(aiSubscriptions.id, id));
|
||||
const report = await subscriptionCostReport(db, c, owner);
|
||||
expect(report.accounts[0].price).toMatchObject({ revision: 500, plan: "Historic plan 499" });
|
||||
expect(report.accounts[0]).not.toHaveProperty("history");
|
||||
expect(JSON.stringify(report)).not.toContain("Historic plan 498");
|
||||
expect(await db.select().from(aiSubscriptionPrices).where(eq(aiSubscriptionPrices.subscriptionId, id))).toHaveLength(501);
|
||||
});
|
||||
it("never lets an admin overwrite another user's personal price or cross a company boundary", async () => {
|
||||
const c = await company(), id = await subscriptionService(db).register(await connection(c));
|
||||
await expect(price(c, id, "10000", {}, other)).rejects.toMatchObject({ status: 403 });
|
||||
await expect(price(await company(), id)).rejects.toMatchObject({ status: 404 });
|
||||
await expect(price(c, id, "10000", {}, { ...owner, readOnly: true })).rejects.toMatchObject({ status: 403 });
|
||||
const input = { expectedRevision: 0, plan: "Plus", amountCents: "1234", currency: "USD" as const, cadence: "month" as const, status: "active" as const };
|
||||
const results = await Promise.allSettled([subscriptionService(db).updatePrice(c, id, input, owner), subscriptionService(db).updatePrice(c, id, { ...input, amountCents: "5678" }, owner)]);
|
||||
expect(results.filter(result => result.status === "fulfilled")).toHaveLength(1);
|
||||
expect(results.filter(result => result.status === "rejected")).toHaveLength(1);
|
||||
});
|
||||
it("commits the price and audit record even if live notification fails", async () => {
|
||||
const c = await company(), id = await subscriptionService(db).register(await connection(c));
|
||||
const publish = vi.spyOn(liveEvents, "publishLiveEvent").mockImplementationOnce(() => { throw new Error("fixture subscriber unavailable"); });
|
||||
try {
|
||||
await expect(price(c, id, "1900")).resolves.toMatchObject({ revision: 1 });
|
||||
expect((await subscriptionCostReport(db, c, owner)).accounts[0].price.amountCents).toBe("1900.0000000");
|
||||
expect(await db.select().from(activityLog).where(and(eq(activityLog.companyId, c), eq(activityLog.action, "subscription.price_updated")))).toHaveLength(1);
|
||||
} finally { publish.mockRestore(); }
|
||||
});
|
||||
it("merges duplicate usage once and retains the selected price", async () => {
|
||||
const c = await company(), service = subscriptionService(db);
|
||||
const a = await service.register(await connection(c, "claude-token-a", "anthropic"));
|
||||
const b = await service.register(await connection(c, "claude-token-b", "anthropic"));
|
||||
await price(c, a, "10000"); await price(c, b, "20000");
|
||||
await event(c, a, "subscription_included"); await event(c, b, "subscription_overage", "200");
|
||||
await service.merge(c, a, b, 1, 1, owner);
|
||||
const report = await subscriptionCostReport(db, c, owner, { allTime: true });
|
||||
expect(report.activeCount).toBe(1);
|
||||
expect(report.monthlyTotals[0].amountCents).toBe("20000.0000000");
|
||||
expect(report.accounts[0].usage).toMatchObject({ eventCount: 2, inputTokens: 200, cachedInputTokens: 80, outputTokens: 20, costCents: "200.0000000" });
|
||||
expect(report.accounts[0].agents).toHaveLength(2);
|
||||
await expect(service.merge(c, b, a, 1, 2, owner)).rejects.toMatchObject({ status: 409 });
|
||||
const different = await service.register(await connection(c));
|
||||
await expect(service.merge(c, b, different, 1, 0, owner)).rejects.toMatchObject({ status: 409 });
|
||||
});
|
||||
it("separates API, subscriptions, overages and other billing with exclusive cache counters", async () => {
|
||||
const c = await company(), id = await verifiedConnection(await connection(c));
|
||||
await event(c, null, "metered_api", "123"); await event(c, id, "subscription_included");
|
||||
await event(c, id, "subscription_overage", "456"); await event(c, null, "unknown", "789");
|
||||
await event(c, null, "credits", "100"); await event(c, null, "fixed", "200");
|
||||
await event(c, null, "subscription_included"); await event(c, id, "subscription_included", "0", new Date("2026-09-01"));
|
||||
const report = await subscriptionCostReport(db, c, owner, { from: new Date("2026-10-01"), to: new Date("2026-11-01") });
|
||||
expect(report.api.costCents).toBe("123.0000000");
|
||||
expect(report.subscription.costCents).toBe("456.0000000");
|
||||
expect(report.subscription.inputTokens + report.subscription.cachedInputTokens + report.subscription.outputTokens).toBe(450);
|
||||
expect(report.unknown.costCents).toBe("1089.0000000");
|
||||
expect(report.unknown.eventCount).toBe(3);
|
||||
expect(report.unknown.inputTokens + report.unknown.cachedInputTokens + report.unknown.outputTokens).toBe(450);
|
||||
expect(report.unattributedSubscription.eventCount).toBe(1);
|
||||
expect(report.accounts[0].usage.eventCount).toBe(2);
|
||||
expect(report.monthlyTotals[0].amountCents).toBe("2000.0000000");
|
||||
});
|
||||
it("snapshots account attribution, rejects forged attribution, and preserves receipt replay", async () => {
|
||||
const c = await company(), input = await connection(c), service = subscriptionService(db);
|
||||
const original = await service.register(input);
|
||||
const agentId = randomUUID(), runId = randomUUID();
|
||||
await db.insert(agents).values({ id: agentId, companyId: c, name: "Codie", role: "engineer", adapterType: "codex_local" });
|
||||
await db.insert(heartbeatRuns).values({ id: runId, companyId: c, agentId, invocationSource: "on_demand", status: "succeeded", contextSnapshot: { aiConnection: { subscriptionId: original, provider: "openai" } } });
|
||||
const replacement = await service.register({ ...input, credential: token("other-workspace") });
|
||||
expect(replacement).not.toBe(original);
|
||||
const receipt = { agentId, heartbeatRunId: runId, idempotencyKey: "subscription-test", provider: "openai", billingType: "subscription_included" as const, model: "fixture", inputTokens: 10, costCents: "0", occurredAt: new Date() };
|
||||
const saved = await costService(db).createEvent(c, { ...receipt, subscriptionId: replacement });
|
||||
expect(saved.subscriptionId).toBe(original);
|
||||
expect((await costService(db).createEvent(c, receipt)).id).toBe(saved.id);
|
||||
const report = await subscriptionCostReport(db, c, owner, { allTime: true });
|
||||
expect(report.accounts.find(row => row.id === original)?.usage.eventCount).toBe(1);
|
||||
expect(report.accounts.find(row => row.id === replacement)?.usage.eventCount).toBe(0);
|
||||
// Legacy or foreign context must not make a valid receipt fail or leak an account.
|
||||
const foreign = await service.register(await connection(await company()));
|
||||
for (const subscriptionId of ["malformed-legacy-id", foreign]) {
|
||||
await db.update(heartbeatRuns).set({ contextSnapshot: { aiConnection: { subscriptionId, provider: "openai" } } }).where(eq(heartbeatRuns.id, runId));
|
||||
const unlinked = await costService(db).createEvent(c, { ...receipt, idempotencyKey: subscriptionId });
|
||||
expect(unlinked.subscriptionId).toBeNull();
|
||||
}
|
||||
});
|
||||
it("preserves successful observations and manual prices through provider failures", async () => {
|
||||
const c = await company(), input = await connection(c), service = subscriptionService(db), id = await service.register(input);
|
||||
const request = fixtureRequest(usage());
|
||||
await Promise.all([refreshSubscriptionConnection(db, input, id, request), refreshSubscriptionConnection(db, input, id, request)]);
|
||||
expect(request).toHaveBeenCalledTimes(1);
|
||||
await refreshSubscriptionConnection(db, input, id, request);
|
||||
expect(request).toHaveBeenCalledTimes(1);
|
||||
await price(c, id, "1750");
|
||||
await db.update(aiSubscriptions).set({ lastCheckedAt: new Date(0) }).where(eq(aiSubscriptions.id, id));
|
||||
await refreshSubscriptionConnection(db, input, id, vi.fn<typeof fetch>().mockRejectedValue(new Error("SECRET raw provider failure")));
|
||||
const report = await subscriptionCostReport(db, c, owner);
|
||||
expect(report.accounts[0]).toMatchObject({ detectedPlan: "plus", refreshStatus: "unavailable", price: { amountCents: "1750.0000000" } });
|
||||
expect(report.accounts[0].observedAt).not.toBeNull();
|
||||
expect(JSON.stringify(report)).not.toContain("SECRET");
|
||||
await db.update(aiSubscriptions).set({ lastCheckedAt: new Date(0) }).where(eq(aiSubscriptions.id, id));
|
||||
await refreshSubscriptionConnection(db, input, id, fixtureRequest(usage("pro")));
|
||||
expect((await subscriptionCostReport(db, c, owner)).accounts[0].price.amountCents).toBe("1750.0000000");
|
||||
});
|
||||
it("ignores a delayed provider observation after reconnecting another account", async () => {
|
||||
const c = await company(), input = await connection(c), service = subscriptionService(db), id = await service.register(input);
|
||||
let finish!: (response: Response) => void;
|
||||
let started!: () => void;
|
||||
const ready = new Promise<void>(resolve => { started = resolve; });
|
||||
const request = vi.fn<typeof fetch>().mockImplementation(() => { started(); return new Promise<Response>(resolve => { finish = resolve; }); });
|
||||
const pending = refreshSubscriptionConnection(db, input, id, request);
|
||||
await ready;
|
||||
const next = await service.register({ ...input, credential: token("new-workspace") });
|
||||
finish(Response.json(usage("pro"))); await pending;
|
||||
const [binding] = await db.select().from(aiSubscriptionConnections).where(and(eq(aiSubscriptionConnections.companyId, c), eq(aiSubscriptionConnections.grantId, input.grantId)));
|
||||
expect(binding.subscriptionId).toBe(next);
|
||||
expect((await db.select().from(aiSubscriptions).where(eq(aiSubscriptions.id, next)))[0].detectedPlan).toBe("plus");
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,9 @@
|
||||
import { importProviderDailyCosts } from "../services/provider-billing-import.js";
|
||||
import { subscriptionPriceSchema, mergeSubscriptionsSchema } from "@paperclipai/shared";
|
||||
import { subscriptionService } from "../services/subscriptions.js";
|
||||
import { subscriptionCostReport } from "../services/subscription-report.js";
|
||||
import { refreshCompanySubscriptions } from "../services/subscription-refresh.js";
|
||||
import { canManageAiConnections } from "./ai-connections.js";
|
||||
import { importProviderCostsSchema } from "@paperclipai/shared";
|
||||
import { accountingIntegrityService } from "../services/accounting-integrity.js";
|
||||
import { billingReconciliationService } from "../services/billing-reconciliation.js";
|
||||
@@ -79,6 +84,44 @@ export function costRoutes(
|
||||
const issues = issueService(db);
|
||||
const access = accessService(db);
|
||||
|
||||
async function subscriptionActor(req: Parameters<typeof assertCompanyAccess>[0], companyId: string) {
|
||||
assertBoard(req);
|
||||
assertCompanyAccess(req, companyId);
|
||||
return { userId: getActorInfo(req).actorId, canManage: await canManageAiConnections(db, req, companyId),
|
||||
readOnly: req.actor.memberships?.some(member => member.companyId === companyId && member.membershipRole === "viewer") ?? false };
|
||||
}
|
||||
|
||||
router.get("/companies/:companyId/costs/subscriptions", async (req, res) => {
|
||||
const companyId = req.params.companyId as string;
|
||||
const actor = await subscriptionActor(req, companyId);
|
||||
if (!(await assertCompanyCostReadAllowed(req, res, companyId))) return;
|
||||
res.json(await subscriptionCostReport(db, companyId, actor, parseCostDateRange(req.query)));
|
||||
});
|
||||
router.post("/companies/:companyId/costs/subscriptions/refresh", async (req, res) => {
|
||||
const companyId = req.params.companyId as string;
|
||||
const actor = await subscriptionActor(req, companyId);
|
||||
if (!(await assertCompanyCostReadAllowed(req, res, companyId))) return;
|
||||
if (actor.readOnly) throw forbidden("Viewers cannot refresh subscription accounts");
|
||||
void refreshCompanySubscriptions(db, companyId, actor.userId);
|
||||
res.status(202).json({ status: "accepted" });
|
||||
});
|
||||
router.patch("/companies/:companyId/costs/subscriptions/:subscriptionId", validate(subscriptionPriceSchema), async (req, res) => {
|
||||
const companyId = req.params.companyId as string;
|
||||
const actor = await subscriptionActor(req, companyId);
|
||||
if (!(await assertCompanyCostReadAllowed(req, res, companyId))) return;
|
||||
const id = z.string().uuid().safeParse(req.params.subscriptionId);
|
||||
if (!id.success) throw badRequest("Invalid subscription ID");
|
||||
res.json(await subscriptionService(db).updatePrice(companyId, id.data, req.body, actor));
|
||||
});
|
||||
router.post("/companies/:companyId/costs/subscriptions/:subscriptionId/link", validate(mergeSubscriptionsSchema), async (req, res) => {
|
||||
const companyId = req.params.companyId as string;
|
||||
const actor = await subscriptionActor(req, companyId);
|
||||
if (!(await assertCompanyCostReadAllowed(req, res, companyId))) return;
|
||||
const id = z.string().uuid().safeParse(req.params.subscriptionId);
|
||||
if (!id.success) throw badRequest("Invalid subscription ID");
|
||||
res.json(await subscriptionService(db).merge(companyId, id.data, req.body.targetId, req.body.expectedRevision, req.body.targetRevision, actor));
|
||||
});
|
||||
|
||||
async function resolveIssueByRef(rawId: string) {
|
||||
const identifier = normalizeIssueIdentifier(rawId);
|
||||
if (identifier) {
|
||||
|
||||
@@ -9,6 +9,7 @@ import { agentService } from "../services/agents.js";
|
||||
import { notFound } from "../errors.js";
|
||||
import { accessService } from "../services/access.js";
|
||||
import { dotRunnerBroker } from "../services/dot-runner-broker.js";
|
||||
import { canConfigureAgentConnection } from "../modules/agent-lifecycle/index.js";
|
||||
|
||||
export function dotRunnerRoutes(db: Db, resourceUrl?: string) {
|
||||
const router = Router();
|
||||
@@ -48,7 +49,14 @@ export function dotRunnerRoutes(db: Db, resourceUrl?: string) {
|
||||
const agent = await agentService(db).getById(input.agentId);
|
||||
if (!agent || agent.companyId !== input.companyId) throw notFound("Agent not found");
|
||||
const config = resourceUrl ? null : publicMcpConfig(process.env);
|
||||
res.json({ agentStatus: agent.status, enabled: await broker.enabled(), resourceUrl: resourceUrl ?? (config ? config.origin + "/mcp/runner" : null), binding: await broker.bindingForAgent(input.companyId, input.agentId) });
|
||||
res.json({
|
||||
agentStatus: agent.status,
|
||||
agentLifecycleState: agent.lifecycleState,
|
||||
canConfigureConnection: canConfigureAgentConnection(agent),
|
||||
enabled: await broker.enabled(),
|
||||
resourceUrl: resourceUrl ?? (config ? config.origin + "/mcp/runner" : null),
|
||||
binding: await broker.bindingForAgent(input.companyId, input.agentId),
|
||||
});
|
||||
});
|
||||
router.post(path, async (req, res) => {
|
||||
const input = scope(req, true);
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
experimentalApiQueries,
|
||||
} from "./experimental-api-paths.js";
|
||||
import { Router } from "express";
|
||||
import { subscriptionPriceSchema, mergeSubscriptionsSchema } from "@paperclipai/shared";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
createAiConnectionSchema,
|
||||
@@ -5567,6 +5568,7 @@ const costSummaryPaths = [
|
||||
"finance-events",
|
||||
"window-spend",
|
||||
"quota-windows",
|
||||
"subscriptions",
|
||||
] as const;
|
||||
|
||||
for (const segment of costSummaryPaths) {
|
||||
@@ -5585,6 +5587,26 @@ for (const segment of costSummaryPaths) {
|
||||
});
|
||||
}
|
||||
|
||||
registry.registerPath({ method: "post", path: "/api/companies/{companyId}/costs/subscriptions/refresh", tags: ["costs"],
|
||||
summary: "Refresh connected subscription estimates in the background",
|
||||
description: "Board members only. Probes only credentials the caller can use. Successful observations are cached for six hours; provider failures retain prior estimates. No inference requests, invoices, or budget charges are created.",
|
||||
request: { params: z.object({ companyId: z.string() }) },
|
||||
responses: { 202: { description: "Background refresh accepted" }, 401: r.unauthorized, 403: r.forbidden,
|
||||
429: { description: "Discovery capacity is full; retry the request later" } },
|
||||
});
|
||||
registry.registerPath({ method: "patch", path: "/api/companies/{companyId}/costs/subscriptions/{subscriptionId}", tags: ["costs"],
|
||||
summary: "Set a subscription price or end tracking",
|
||||
description: "Owner only for personal subscriptions; connection managers for shared subscriptions. Appends price history from now. Expected revision prevents lost updates. Ending tracking does not cancel provider billing. Monthly estimates never change recorded charges or agent budgets.",
|
||||
request: { params: z.object({ companyId: z.string(), subscriptionId: z.string().uuid() }), body: jsonBody(subscriptionPriceSchema) },
|
||||
responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, 404: r.notFound, 409: r.conflict },
|
||||
});
|
||||
registry.registerPath({ method: "post", path: "/api/companies/{companyId}/costs/subscriptions/{subscriptionId}/link", tags: ["costs"],
|
||||
summary: "Link duplicate subscription accounts",
|
||||
description: "Requires editing permission on both accounts in this company. Combines their usage, counts the fee once, and keeps the target price. Historical run IDs and price history are preserved.",
|
||||
request: { params: z.object({ companyId: z.string(), subscriptionId: z.string().uuid() }), body: jsonBody(mergeSubscriptionsSchema) },
|
||||
responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, 404: r.notFound, 409: r.conflict },
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
method: "post",
|
||||
path: "/api/companies/{companyId}/cost-events",
|
||||
|
||||
@@ -12,6 +12,8 @@ import {
|
||||
} from "@paperclipai/shared";
|
||||
import { managedProviderRouting } from "./ai-provider-routing.js";
|
||||
import { aiConnectionService } from "./ai-connections.js";
|
||||
import { subscriptionService } from "./subscriptions.js";
|
||||
import { refreshSubscriptionConnection } from "./subscription-refresh.js";
|
||||
import { secretService } from "./secrets.js";
|
||||
import { decideCodexAuthMerge, withAccountHomeSecretMutationLock } from "@paperclipai/adapter-codex-local/server";
|
||||
import { WORKSPACE_RESTORE_LOCK_TIMEOUT_CODE } from "@paperclipai/adapter-utils/workspace-restore-merge";
|
||||
@@ -354,6 +356,16 @@ export async function prepareManagedAiRuntime(
|
||||
if (projected.hermesConfig) await writeFile(path.join(providerHome, "config.yaml"), projected.hermesConfig, { mode: 0o600 });
|
||||
if (projected.codexConfig) await writeFile(path.join(providerHome, "config.toml"), 'cli_auth_credentials_store = "file"\n' + projected.codexConfig, { mode: 0o600 });
|
||||
}
|
||||
const attribution = { ...selection.attribution } as typeof selection.attribution & { subscriptionId?: string };
|
||||
if (attribution.method === "subscription") {
|
||||
const subscription = {
|
||||
companyId: input.companyId, connectionId: selection.connection.id, grantId: selection.grant.id,
|
||||
provider: selection.attribution.provider, name: selection.connection.name,
|
||||
ownerUserId: selection.grant.subjectUserId, credential: value,
|
||||
};
|
||||
attribution.subscriptionId = await subscriptionService(db).register(subscription);
|
||||
void refreshSubscriptionConnection(db, subscription, attribution.subscriptionId);
|
||||
}
|
||||
const generation = createHash("sha256")
|
||||
.update(value)
|
||||
.digest("hex")
|
||||
@@ -367,9 +379,9 @@ export async function prepareManagedAiRuntime(
|
||||
...projected?.config,
|
||||
...(routing ? { managedAiRouting: routing } : {}),
|
||||
env,
|
||||
managedAiConnection: { ...selection.attribution, identity, sessionIdentity },
|
||||
managedAiConnection: { ...attribution, identity, sessionIdentity },
|
||||
},
|
||||
attribution: selection.attribution,
|
||||
attribution,
|
||||
accountName: selection.connection.name,
|
||||
accountOwnerUserId: selection.grant.subjectUserId,
|
||||
identity,
|
||||
|
||||
@@ -63,7 +63,7 @@ class ProbeFailure extends Error {
|
||||
constructor(readonly code: NonNullable<AiConnectionUsage["errorCode"]>) { super(code); }
|
||||
}
|
||||
|
||||
async function readUsage(url: string, headers: Record<string, string>, request: typeof fetch): Promise<ObjectValue> {
|
||||
export async function readUsage(url: string, headers: Record<string, string>, request: typeof fetch): Promise<ObjectValue> {
|
||||
// Fixed origins, no redirects, and a deadline covering headers AND response bytes.
|
||||
const response = await request(url, {
|
||||
headers, redirect: "error", signal: AbortSignal.timeout(15000),
|
||||
|
||||
@@ -1084,15 +1084,15 @@ export function aiConnectionService(db: Db) {
|
||||
}
|
||||
// A quota read uses the same credential audience as execution. Operator status
|
||||
// alone never grants access to another member's personal subscription.
|
||||
async function quotaAccounts(companyId: string, userId: string) {
|
||||
async function quotaAccounts(companyId: string, userId: string, includeOtherProviders = false) {
|
||||
if (!(await membership(companyId, userId))) return [];
|
||||
const visible = await list(companyId, userId);
|
||||
const accounts = await rows(companyId);
|
||||
return accounts.flatMap(row => {
|
||||
const summary = visible.find(item => item.id === row.connection.id && item.grantId === row.grant.id);
|
||||
if (!summary || summary.method !== "subscription" || !["openai", "anthropic"].includes(summary.provider)) return [];
|
||||
if (!summary || summary.method !== "subscription" || !(includeOtherProviders ? ["openai", "anthropic", "xai"] : ["openai", "anthropic"]).includes(summary.provider)) return [];
|
||||
return [{ ...row, summary }];
|
||||
});
|
||||
}
|
||||
return { list, selectDecision, quotaAccounts, refreshQuotaCredential, select, credential, runtimeCredential, probeUsage, save, setDefault, membership, markAuthenticationFailed };
|
||||
return { list, selectDecision, quotaAccounts, subscriptionAccounts: (companyId: string, userId: string) => quotaAccounts(companyId, userId, true), refreshQuotaCredential, select, credential, runtimeCredential, probeUsage, save, setDefault, membership, markAuthenticationFailed };
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
import { receiptFingerprint } from "./receipt-fingerprint.js";
|
||||
import { agentAvatarUrl, resolveAgentAppearance, createCostEventSchema, createServiceCostEventSchema, normalizeCents, type MoneyInput, type CostByUserReport } from "@paperclipai/shared";
|
||||
import { agentAvatarUrl, resolveAgentAppearance, createCostEventSchema, createServiceCostEventSchema, normalizeCents, isUuidLike, type MoneyInput, type CostByUserReport } from "@paperclipai/shared";
|
||||
import { and, desc, eq, gte, inArray, isNotNull, isNull, lt, lte, ne, sql } from "drizzle-orm";
|
||||
import { alias } from "drizzle-orm/pg-core";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { activityLog, agents, agentRuntimeState, authUsers, companies, companyMemberships, costEvents, heartbeatRuns, issues, projects, goals } from "@paperclipai/db";
|
||||
import { activityLog, agents, agentRuntimeState, authUsers, companies, companyMemberships, costEvents, heartbeatRuns, issues, projects, goals, aiSubscriptions } from "@paperclipai/db";
|
||||
import { notFound, unprocessable, conflict } from "../errors.js";
|
||||
import { budgetService, budgetServiceInTransaction, type BudgetServiceHooks } from "./budgets.js";
|
||||
import { logActivity, type LogActivityInput, type ActivityPublication } from "./activity-log.js";
|
||||
@@ -20,7 +20,7 @@ const SUBSCRIPTION_BILLING_TYPES = ["subscription_included", "subscription_overa
|
||||
// provider-qualified model IDs and already excluded cache reads. Normalize each
|
||||
// historical row before aggregation so mixed old/new groups share the current
|
||||
// exclusive-input contract. Preserve the original ledger and monetary amounts.
|
||||
const ordinaryInputTokens = sql<number>`case
|
||||
export const ordinaryInputTokens = sql<number>`case
|
||||
when ${costEvents.receiptHash} is null and ${costEvents.provider} = 'openai'
|
||||
and ${costEvents.model} not like 'openai/_%'
|
||||
then greatest(0, ${costEvents.inputTokens} - ${costEvents.cachedInputTokens})
|
||||
@@ -124,11 +124,19 @@ export async function createCostEventInTransaction(db: Db, companyId: string, da
|
||||
if (!row) throw notFound(`${label} not found`);
|
||||
if (row.companyId !== companyId) throw unprocessable(`${label} does not belong to company`);
|
||||
}
|
||||
let subscriptionId: string | null = null;
|
||||
if (values.heartbeatRunId) {
|
||||
const [run] = await db.select({ agentId: heartbeatRuns.agentId }).from(heartbeatRuns).where(eq(heartbeatRuns.id, values.heartbeatRunId));
|
||||
const [run] = await db.select({ agentId: heartbeatRuns.agentId, context: heartbeatRuns.contextSnapshot }).from(heartbeatRuns).where(eq(heartbeatRuns.id, values.heartbeatRunId));
|
||||
if (run.agentId !== values.agentId) throw unprocessable("Heartbeat run does not belong to agent");
|
||||
const attribution = run.context?.aiConnection as { subscriptionId?: unknown; provider?: unknown } | undefined;
|
||||
if (SUBSCRIPTION_BILLING_TYPES.includes(values.billingType as typeof SUBSCRIPTION_BILLING_TYPES[number]) && attribution?.provider === values.provider && typeof attribution.subscriptionId === "string" && isUuidLike(attribution.subscriptionId)) {
|
||||
const [account] = await db.select({ id: aiSubscriptions.id }).from(aiSubscriptions).where(and(eq(aiSubscriptions.id, attribution.subscriptionId), eq(aiSubscriptions.companyId, companyId), eq(aiSubscriptions.provider, values.provider)));
|
||||
subscriptionId = account?.id ?? null;
|
||||
}
|
||||
}
|
||||
const [event] = await db.insert(costEvents).values({ ...values, costCents: sql`${values.costCents}::numeric`, reportedCostCents: values.costCents, id: data.id, companyId, receiptHash }).returning();
|
||||
// Server-derived attribution stays outside the immutable receipt fingerprint;
|
||||
// replaying a receipt must not depend on later account metadata changes.
|
||||
const [event] = await db.insert(costEvents).values({ ...values, subscriptionId, costCents: sql`${values.costCents}::numeric`, reportedCostCents: values.costCents, id: data.id, companyId, receiptHash }).returning();
|
||||
await updateMonthlySpendProjections(db, companyId, event.agentId, values.costCents, event.occurredAt);
|
||||
// Separately reported charges linked to an already-accounted run contribute
|
||||
// to lifetime totals too. Before acknowledgement, accountRunCost includes
|
||||
@@ -676,6 +684,8 @@ export function costService(db: Db, budgetHooks: BudgetServiceHooks = {}) {
|
||||
.select({
|
||||
projectId: projects.id,
|
||||
projectName: projects.name,
|
||||
eventCount: sql<number>`count(*)::int`,
|
||||
estimatedEventCount: sql<number>`count(*) filter (where ${costEvents.costStatus} = 'estimated')::int`,
|
||||
costCents: costCentsExpr,
|
||||
costCentsExact: sql<string>`coalesce(sum(${costEvents.costCents}), 0)::text`,
|
||||
inputTokens: sumAsNumber(ordinaryInputTokens),
|
||||
|
||||
+28
-1171
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,284 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import {
|
||||
agents, agentSessionGoalActions, agentTaskSessions, companies, createDb,
|
||||
EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, heartbeatRuns, issues,
|
||||
} from "@paperclipai/db";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js";
|
||||
import { conflict } from "../../errors.js";
|
||||
import { createHeartbeatRunPreparation } from "./run-preparation.js";
|
||||
import { createHeartbeatRunState } from "./run-state.js";
|
||||
import { createHeartbeatScheduling, type HeartbeatSchedulingDependencies } from "./scheduling.js";
|
||||
|
||||
vi.mock("../live-events.js", () => ({ publishLiveEvent: vi.fn() }));
|
||||
|
||||
type Run = typeof heartbeatRuns.$inferSelect;
|
||||
const now = new Date("2026-10-09T12:00:00.000Z");
|
||||
const dueAt = new Date(now.getTime() - 60_000);
|
||||
const admitted = { id: "admitted-run" } as Run;
|
||||
const timerPolicy = {
|
||||
enabled: false, intervalSec: 60, wakeOnDemand: true, maxConcurrentRuns: 1,
|
||||
skipTimerWhenNoActionableWork: false, maxDailyRuns: null, maxDailyCostCents: null,
|
||||
};
|
||||
|
||||
function callbacks(db: Db) {
|
||||
const state = createHeartbeatRunState(db);
|
||||
const preparation = createHeartbeatRunPreparation(db);
|
||||
return {
|
||||
getAgent: state.getAgent,
|
||||
getRun: state.getRun,
|
||||
toAgentOrgRow: preparation.toAgentOrgRow,
|
||||
groupAgentOrgRowsByCompany: preparation.groupAgentOrgRowsByCompany,
|
||||
issuesSvc: {
|
||||
listReviewAttention: vi.fn<HeartbeatSchedulingDependencies["issuesSvc"]["listReviewAttention"]>(async () => new Map()),
|
||||
create: vi.fn<HeartbeatSchedulingDependencies["issuesSvc"]["create"]>(),
|
||||
},
|
||||
enqueueWakeup: vi.fn<HeartbeatSchedulingDependencies["enqueueWakeup"]>(async () => admitted),
|
||||
scheduleBoundedRetryForRun: vi.fn<HeartbeatSchedulingDependencies["scheduleBoundedRetryForRun"]>(),
|
||||
getSchedulingSuppression: vi.fn(async () => ({ suppressed: false })),
|
||||
getWorktreeExecutionCutoff: vi.fn<HeartbeatSchedulingDependencies["getWorktreeExecutionCutoff"]>(async () => null),
|
||||
parseHeartbeatPolicy: vi.fn<HeartbeatSchedulingDependencies["parseHeartbeatPolicy"]>(() => timerPolicy),
|
||||
claimDueTimerHeartbeat: vi.fn<HeartbeatSchedulingDependencies["claimDueTimerHeartbeat"]>(async () => ({ wasFirstHeartbeat: true })),
|
||||
} satisfies HeartbeatSchedulingDependencies;
|
||||
}
|
||||
|
||||
describe("heartbeat scheduling module boundary", () => {
|
||||
function guardedDatabase() {
|
||||
const access = vi.fn(() => { throw new Error("Unexpected scheduling database access"); });
|
||||
return { db: new Proxy({}, { get: access }) as Db, access };
|
||||
}
|
||||
|
||||
it("constructs without querying, admitting work, or starting timers", () => {
|
||||
const database = guardedDatabase();
|
||||
const deps = callbacks(database.db);
|
||||
createHeartbeatScheduling(database.db, deps);
|
||||
expect(database.access).not.toHaveBeenCalled();
|
||||
for (const callback of Object.values(deps)) if (vi.isMockFunction(callback)) expect(callback).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(["tickTimers", "recoverActiveSessionGoals", "recoverPendingSessionGoalActions"] as const)(
|
||||
"honors suppression before %s reads or admits work", async (operation) => {
|
||||
const database = guardedDatabase();
|
||||
const deps = callbacks(database.db);
|
||||
deps.getSchedulingSuppression.mockResolvedValue({ suppressed: true });
|
||||
const result = await createHeartbeatScheduling(database.db, deps)[operation]();
|
||||
expect(Object.values(result).every(value => value === 0)).toBe(true);
|
||||
expect(database.access).not.toHaveBeenCalled();
|
||||
expect(deps.enqueueWakeup).not.toHaveBeenCalled();
|
||||
expect(deps.claimDueTimerHeartbeat).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
const postgres = await getEmbeddedPostgresTestSupport();
|
||||
describe.skipIf(!postgres.supported)("heartbeat scheduling database boundary", () => {
|
||||
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
||||
let db: Db;
|
||||
beforeAll(async () => {
|
||||
database = await startEmbeddedPostgresTestDatabase("paperclip-heartbeat-scheduling-module");
|
||||
db = createDb(database.connectionString);
|
||||
}, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS);
|
||||
afterAll(async () => {
|
||||
await db?.$client.end();
|
||||
await database?.cleanup();
|
||||
});
|
||||
beforeEach(async () => {
|
||||
await db.execute(sql`truncate table companies restart identity cascade`);
|
||||
});
|
||||
|
||||
async function fixture() {
|
||||
const [company] = await db.insert(companies).values({ name: "Scheduling", issuePrefix: "SCH" }).returning();
|
||||
const [agent] = await db.insert(agents).values({ companyId: company.id, name: "Scheduled agent", adapterType: "paperclip_runner", createdAt: dueAt }).returning();
|
||||
const [issue] = await db.insert(issues).values({
|
||||
companyId: company.id, title: "Check deployment", status: "in_progress", assigneeAgentId: agent.id,
|
||||
monitorNextCheckAt: dueAt, monitorAttemptCount: 0, createdAt: dueAt,
|
||||
executionPolicy: { mode: "normal", commentRequired: true, stages: [], monitor: { nextCheckAt: dueAt.toISOString() } },
|
||||
}).returning();
|
||||
const deps = callbacks(db);
|
||||
return { company, agent, issue, deps, scheduler: createHeartbeatScheduling(db, deps) };
|
||||
}
|
||||
async function readIssue(id: string) {
|
||||
return db.select().from(issues).where(eq(issues.id, id)).then(rows => rows[0]!);
|
||||
}
|
||||
async function session(f: Awaited<ReturnType<typeof fixture>>, patch: Partial<typeof agentTaskSessions.$inferInsert> = {}) {
|
||||
return db.insert(agentTaskSessions).values({
|
||||
companyId: f.company.id, agentId: f.agent.id, adapterType: f.agent.adapterType, taskKey: f.issue.id,
|
||||
goalDesiredState: "active", goalStatus: "active", goalRevision: 7, ...patch,
|
||||
}).returning().then(rows => rows[0]!);
|
||||
}
|
||||
function enableTimer(deps: ReturnType<typeof callbacks>) {
|
||||
deps.parseHeartbeatPolicy.mockReturnValue({ ...timerPolicy, enabled: true });
|
||||
deps.parseHeartbeatPolicy.mockClear();
|
||||
}
|
||||
|
||||
it("shares database monitor claims across scheduler instances", async () => {
|
||||
const f = await fixture();
|
||||
let release!: () => void;
|
||||
let entered!: () => void;
|
||||
const started = new Promise<void>(resolve => { entered = resolve; });
|
||||
const hold = new Promise<void>(resolve => { release = resolve; });
|
||||
f.deps.enqueueWakeup.mockImplementationOnce(async () => { entered(); await hold; return admitted; });
|
||||
const first = f.scheduler.tickTimers(now);
|
||||
try {
|
||||
await started;
|
||||
const second = createHeartbeatScheduling(db, f.deps);
|
||||
expect(await second.tickTimers(now)).toEqual({ checked: 0, enqueued: 0, skipped: 0 });
|
||||
await expect(second.triggerIssueMonitor(f.issue.id, { now })).rejects.toThrow("already in progress");
|
||||
} finally {
|
||||
release();
|
||||
await first;
|
||||
}
|
||||
expect(f.deps.enqueueWakeup).toHaveBeenCalledTimes(1);
|
||||
expect(await readIssue(f.issue.id)).toMatchObject({ monitorNextCheckAt: null, monitorAttemptCount: 1 });
|
||||
});
|
||||
|
||||
it("preserves a replacement schedule written during wake admission", async () => {
|
||||
const f = await fixture();
|
||||
const replacement = new Date(now.getTime() + 60_000);
|
||||
f.deps.enqueueWakeup.mockImplementationOnce(async () => {
|
||||
await db.update(issues).set({ monitorNextCheckAt: replacement, monitorWakeRequestedAt: null }).where(eq(issues.id, f.issue.id));
|
||||
return admitted;
|
||||
});
|
||||
expect(await f.scheduler.tickTimers(now)).toEqual({ checked: 1, enqueued: 0, skipped: 1 });
|
||||
expect(await readIssue(f.issue.id)).toMatchObject({ monitorNextCheckAt: replacement, monitorAttemptCount: 0 });
|
||||
});
|
||||
|
||||
it("retains a deferred monitor and releases its claim for a later tick", async () => {
|
||||
const f = await fixture();
|
||||
f.deps.enqueueWakeup.mockResolvedValueOnce(null);
|
||||
expect(await f.scheduler.tickTimers(now)).toEqual({ checked: 1, enqueued: 0, skipped: 1 });
|
||||
expect(await readIssue(f.issue.id)).toMatchObject({ monitorNextCheckAt: dueAt, monitorWakeRequestedAt: null, monitorAttemptCount: 0 });
|
||||
expect(await f.scheduler.tickTimers(now)).toEqual({ checked: 1, enqueued: 1, skipped: 0 });
|
||||
const calls = f.deps.enqueueWakeup.mock.calls;
|
||||
expect(calls[0]![1]!.idempotencyKey).toBe(calls[1]![1]!.idempotencyKey);
|
||||
expect(calls[0]![1]!.issueStateGuard).toMatchObject({
|
||||
assigneeAgentId: f.agent.id, statuses: ["in_progress"], monitorNextCheckAt: dueAt.toISOString(), monitorWakeRequestedAt: now.toISOString(),
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps manual error recovery distinct from scheduled client-error handling", async () => {
|
||||
const f = await fixture();
|
||||
f.deps.enqueueWakeup.mockRejectedValue(conflict("Agent is paused"));
|
||||
await expect(f.scheduler.triggerIssueMonitor(f.issue.id, { now, actorType: "user", actorId: "board-user" })).rejects.toThrow("Agent is paused");
|
||||
expect(await readIssue(f.issue.id)).toMatchObject({ monitorNextCheckAt: dueAt, monitorWakeRequestedAt: null });
|
||||
expect(f.deps.enqueueWakeup).toHaveBeenLastCalledWith(f.agent.id, expect.objectContaining({
|
||||
source: "on_demand", requestedByActorType: "user", requestedByActorId: "board-user",
|
||||
}));
|
||||
expect(await f.scheduler.tickTimers(now)).toEqual({ checked: 1, enqueued: 0, skipped: 1 });
|
||||
expect(await readIssue(f.issue.id)).toMatchObject({ monitorNextCheckAt: null });
|
||||
});
|
||||
|
||||
it("retains monitors after transient admission failures", async () => {
|
||||
const f = await fixture();
|
||||
f.deps.enqueueWakeup.mockRejectedValueOnce(new Error("Temporary admission failure"));
|
||||
await f.scheduler.tickTimers(now);
|
||||
expect(await readIssue(f.issue.id)).toMatchObject({ monitorNextCheckAt: dueAt, monitorWakeRequestedAt: null });
|
||||
expect(await f.scheduler.tickTimers(now)).toEqual({ checked: 1, enqueued: 1, skipped: 0 });
|
||||
});
|
||||
|
||||
it("leaves monitors alone while a native run owns the issue", async () => {
|
||||
const f = await fixture();
|
||||
const [run] = await db.insert(heartbeatRuns).values({ companyId: f.company.id, agentId: f.agent.id, nativeIssueId: f.issue.id, runtimeMode: "native", status: "running", contextSnapshot: { issueId: f.issue.id } }).returning();
|
||||
expect(await f.scheduler.tickTimers(now)).toEqual({ checked: 0, enqueued: 0, skipped: 0 });
|
||||
expect(f.deps.enqueueWakeup).not.toHaveBeenCalled();
|
||||
await db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, run!.id));
|
||||
expect(await f.scheduler.tickTimers(now)).toEqual({ checked: 1, enqueued: 1, skipped: 0 });
|
||||
});
|
||||
|
||||
it("skips archived companies for both timers and monitors", async () => {
|
||||
const f = await fixture();
|
||||
enableTimer(f.deps);
|
||||
await db.update(companies).set({ status: "archived" }).where(eq(companies.id, f.company.id));
|
||||
expect(await f.scheduler.tickTimers(now)).toEqual({ checked: 0, enqueued: 0, skipped: 0 });
|
||||
expect(f.deps.claimDueTimerHeartbeat).not.toHaveBeenCalled();
|
||||
expect(f.deps.enqueueWakeup).not.toHaveBeenCalled();
|
||||
expect(await readIssue(f.issue.id)).toMatchObject({ monitorNextCheckAt: dueAt });
|
||||
});
|
||||
|
||||
it("combines timer and monitor counts and passes the timer claim receipt to admission", async () => {
|
||||
const f = await fixture();
|
||||
enableTimer(f.deps);
|
||||
expect(await f.scheduler.tickTimers(now)).toEqual({ checked: 2, enqueued: 2, skipped: 0 });
|
||||
expect(f.deps.claimDueTimerHeartbeat).toHaveBeenCalledWith(expect.objectContaining({ id: f.agent.id }), now, 60);
|
||||
expect(f.deps.enqueueWakeup).toHaveBeenCalledWith(f.agent.id, expect.objectContaining({
|
||||
source: "timer", reason: "heartbeat_timer", contextSnapshot: expect.objectContaining({ timerClaimWasFirstHeartbeat: true }),
|
||||
}));
|
||||
});
|
||||
|
||||
it("does not enqueue a timer after losing its due claim", async () => {
|
||||
const f = await fixture();
|
||||
enableTimer(f.deps);
|
||||
await db.update(issues).set({ monitorNextCheckAt: null }).where(eq(issues.id, f.issue.id));
|
||||
f.deps.claimDueTimerHeartbeat.mockResolvedValue(null);
|
||||
expect(await f.scheduler.tickTimers(now)).toEqual({ checked: 1, enqueued: 0, skipped: 0 });
|
||||
expect(f.deps.enqueueWakeup).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("enforces worktree cutoffs and agent invokability before timer claims", async () => {
|
||||
const f = await fixture();
|
||||
enableTimer(f.deps);
|
||||
await db.update(issues).set({ monitorNextCheckAt: null }).where(eq(issues.id, f.issue.id));
|
||||
f.deps.getWorktreeExecutionCutoff.mockResolvedValue(now);
|
||||
await f.scheduler.tickTimers(now);
|
||||
expect(f.deps.claimDueTimerHeartbeat).not.toHaveBeenCalled();
|
||||
await db.update(issues).set({ createdAt: now }).where(eq(issues.id, f.issue.id));
|
||||
await db.update(agents).set({ status: "paused" }).where(eq(agents.id, f.agent.id));
|
||||
await f.scheduler.tickTimers(now);
|
||||
expect(f.deps.claimDueTimerHeartbeat).not.toHaveBeenCalled();
|
||||
await db.update(agents).set({ status: "idle" }).where(eq(agents.id, f.agent.id));
|
||||
expect(await f.scheduler.tickTimers(now)).toEqual({ checked: 1, enqueued: 1, skipped: 0 });
|
||||
});
|
||||
|
||||
it("recovers active goals with stable revision-based admission keys", async () => {
|
||||
const f = await fixture();
|
||||
const active = await session(f);
|
||||
expect(await f.scheduler.recoverActiveSessionGoals()).toEqual({ scanned: 1, enqueued: 1 });
|
||||
expect(f.deps.enqueueWakeup).toHaveBeenCalledWith(f.agent.id, expect.objectContaining({
|
||||
idempotencyKey: `goal_recovery:${active.id}:7`, contextSnapshot: { issueId: f.issue.id, taskKey: f.issue.id, resumeSessionGoalHeartbeat: true, skipIssueComment: true },
|
||||
}));
|
||||
f.deps.enqueueWakeup.mockResolvedValueOnce(null);
|
||||
expect(await f.scheduler.recoverActiveSessionGoals()).toEqual({ scanned: 1, enqueued: 0 });
|
||||
expect(f.deps.enqueueWakeup.mock.calls[1]![1]!.idempotencyKey).toBe(f.deps.enqueueWakeup.mock.calls[0]![1]!.idempotencyKey);
|
||||
await db.update(issues).set({ status: "done" }).where(eq(issues.id, f.issue.id));
|
||||
expect(await f.scheduler.recoverActiveSessionGoals()).toEqual({ scanned: 0, enqueued: 0 });
|
||||
});
|
||||
|
||||
it("excludes goals after reassignment or with a mismatched company binding", async () => {
|
||||
const f = await fixture();
|
||||
const [other] = await db.insert(companies).values({ name: "Other company", issuePrefix: "OTH" }).returning();
|
||||
const active = await session(f, { companyId: other!.id });
|
||||
expect(await f.scheduler.recoverActiveSessionGoals()).toEqual({ scanned: 0, enqueued: 0 });
|
||||
await db.update(agentTaskSessions).set({ companyId: f.company.id }).where(eq(agentTaskSessions.id, active.id));
|
||||
await db.update(issues).set({ assigneeAgentId: null }).where(eq(issues.id, f.issue.id));
|
||||
expect(await f.scheduler.recoverActiveSessionGoals()).toEqual({ scanned: 0, enqueued: 0 });
|
||||
expect(f.deps.enqueueWakeup).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(["queued", "scheduled_retry", "running"])("deduplicates a pending goal action against a %s run", async status => {
|
||||
const f = await fixture();
|
||||
const active = await session(f);
|
||||
const requestId = randomUUID();
|
||||
const [action] = await db.insert(agentSessionGoalActions).values({ companyId: f.company.id, sessionId: active.id, requestId, action: "pause", payloadJson: { requestId, action: "pause" } }).returning();
|
||||
const [run] = await db.insert(heartbeatRuns).values({ companyId: f.company.id, agentId: f.agent.id, status, contextSnapshot: { goalControlRequestId: requestId } }).returning();
|
||||
expect(await f.scheduler.recoverPendingSessionGoalActions()).toEqual({ scanned: 1, enqueued: 0, alreadyQueued: 1, invalid: 0 });
|
||||
expect(f.deps.enqueueWakeup).not.toHaveBeenCalled();
|
||||
await db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, run!.id));
|
||||
await db.update(issues).set({ status: "done" }).where(eq(issues.id, f.issue.id));
|
||||
expect(await f.scheduler.recoverPendingSessionGoalActions()).toEqual({ scanned: 1, enqueued: 1, alreadyQueued: 0, invalid: 0 });
|
||||
expect(f.deps.enqueueWakeup).toHaveBeenCalledWith(f.agent.id, expect.objectContaining({
|
||||
idempotencyKey: `goal_control_recovery:${action!.id}`, contextSnapshot: expect.objectContaining({ resumeIntent: true, goalControlRequestId: requestId, runnerGoalControl: { requestId, action: "pause" } }),
|
||||
}));
|
||||
});
|
||||
|
||||
it("persists invalid goal actions as failures without wake admission", async () => {
|
||||
const f = await fixture();
|
||||
const active = await session(f);
|
||||
const [action] = await db.insert(agentSessionGoalActions).values({ companyId: f.company.id, sessionId: active.id, requestId: "expected", action: "pause", payloadJson: { requestId: "different", action: "pause" } }).returning();
|
||||
expect(await f.scheduler.recoverPendingSessionGoalActions()).toEqual({ scanned: 1, enqueued: 0, alreadyQueued: 0, invalid: 1 });
|
||||
expect(f.deps.enqueueWakeup).not.toHaveBeenCalled();
|
||||
const failed = await db.select().from(agentSessionGoalActions).where(eq(agentSessionGoalActions.id, action!.id));
|
||||
expect(failed[0]).toMatchObject({ status: "failed", error: "session_goal_control_payload_invalid" });
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,78 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { probeAiConnectionUsage, readUsage } from "./ai-connection-usage.js";
|
||||
import type { AiProvider } from "@paperclipai/shared";
|
||||
|
||||
const object = (value: unknown): Record<string, unknown> => value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
|
||||
const string = (value: unknown): string | null => typeof value === "string" && value.length > 0 && value.length <= 200 ? value : null;
|
||||
function json(value: string): Record<string, unknown> { try { return object(JSON.parse(value)); } catch { return {}; } }
|
||||
function claims(value: unknown) {
|
||||
if (typeof value !== "string" || value.length > 32768) return {};
|
||||
return json(Buffer.from(value.split(".")[1] ?? "", "base64url").toString());
|
||||
}
|
||||
|
||||
export function subscriptionIdentityKey(companyId: string, provider: string, parts: string[]): string {
|
||||
return createHash("sha256").update(JSON.stringify([companyId, provider, ...parts])).digest("hex");
|
||||
}
|
||||
|
||||
export interface SubscriptionIdentity {
|
||||
credentialKey: string;
|
||||
accountKey: string;
|
||||
verified: boolean;
|
||||
plan: string | null;
|
||||
}
|
||||
|
||||
/** Credential-local hints cannot authenticate a provider account. In particular,
|
||||
* a user may edit an ID token independently of the bearer token sent upstream.
|
||||
* No ambient host credentials, emails, raw account IDs, or tokens leave this helper. */
|
||||
export function subscriptionCredentialIdentity(companyId: string, provider: string, credential: string): SubscriptionIdentity {
|
||||
const credentialKey = subscriptionIdentityKey(companyId, provider, ["credential", credential]);
|
||||
const auth = json(credential);
|
||||
let plan: string | null = null;
|
||||
if (provider === "openai") {
|
||||
const tokens = object(auth.tokens);
|
||||
const token = claims(tokens.id_token);
|
||||
const account = object(token["https://api.openai.com/auth"]);
|
||||
plan = string(account.chatgpt_plan_type);
|
||||
}
|
||||
// Other credential formats do not yet prove a stable billing identity. Use a
|
||||
// credential-scoped record until a profile observation or manual link proves it.
|
||||
return { credentialKey, accountKey: credentialKey, verified: false, plan };
|
||||
}
|
||||
|
||||
export async function probeSubscriptionIdentity(companyId: string, provider: AiProvider, credential: string, request: typeof fetch = fetch) {
|
||||
const identity = subscriptionCredentialIdentity(companyId, provider, credential);
|
||||
if (provider === "anthropic") {
|
||||
// Same account-scoped OAuth profile used by Claude Code / CodexBar. A
|
||||
// setup-token may lack user:profile; failure must preserve the prior record.
|
||||
const profile = await readUsage("https://api.anthropic.com/api/oauth/profile", {
|
||||
Authorization: `Bearer ${credential}`, "anthropic-beta": "oauth-2025-04-20",
|
||||
}, request);
|
||||
const account = object(profile.account), organization = object(profile.organization);
|
||||
const seat = string(account.uuid), workspace = string(organization.uuid);
|
||||
const type = string(organization.organization_type);
|
||||
const tier = string(organization.rate_limit_tier);
|
||||
const plan = type === "claude_max" && tier === "default_claude_max_5x" ? "max_5x"
|
||||
: type === "claude_max" && tier === "default_claude_max_20x" ? "max_20x"
|
||||
: ({ claude_pro: "pro", claude_max: "max", claude_team: "team", claude_enterprise: "enterprise" } as Record<string, string>)[type ?? ""] ?? null;
|
||||
if (!seat || !workspace) throw new Error("Subscription profile unavailable");
|
||||
return { ...identity, accountKey: subscriptionIdentityKey(companyId, provider, ["account", workspace, seat]), verified: true, plan };
|
||||
}
|
||||
const usage = await probeAiConnectionUsage({ provider, method: "subscription" }, credential, { request });
|
||||
if (usage.status !== "ok") throw new Error("Subscription profile unavailable");
|
||||
if (provider === "openai") {
|
||||
// The usage request authenticated this exact bearer token with OpenAI.
|
||||
// Only its claims may identify a seat; the separate ID token and editable
|
||||
// account-id field cannot grant billing access. An opaque bearer or a
|
||||
// selected workspace that differs from its claims stays unconfirmed.
|
||||
const auth = json(credential), tokens = object(auth.tokens);
|
||||
const token = claims(tokens.access_token ?? auth.accessToken);
|
||||
const account = object(token["https://api.openai.com/auth"]);
|
||||
const workspace = string(account.chatgpt_account_id);
|
||||
const selectedWorkspace = string(tokens.account_id ?? auth.accountId);
|
||||
const seat = string(account.chatgpt_user_id) ?? string(token.sub);
|
||||
if (workspace && seat && (!selectedWorkspace || selectedWorkspace === workspace)) {
|
||||
return { ...identity, accountKey: subscriptionIdentityKey(companyId, provider, ["account", workspace, seat]), verified: true, plan: string(usage.planType) };
|
||||
}
|
||||
}
|
||||
return { ...identity, plan: string(usage.planType) };
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import { and, eq, lt, or, isNull } from "drizzle-orm";
|
||||
import { aiSubscriptions, aiSubscriptionConnections, type Db } from "@paperclipai/db";
|
||||
import { aiConnectionService } from "./ai-connections.js";
|
||||
import { subscriptionService, type SubscriptionConnection } from "./subscriptions.js";
|
||||
import { probeSubscriptionIdentity } from "./subscription-identity.js";
|
||||
import { logger } from "../middleware/logger.js";
|
||||
import { tooManyRequests } from "../errors.js";
|
||||
|
||||
const jobs = new WeakMap<Db, Map<string, Promise<void>>>();
|
||||
const discovery = new WeakMap<Db, Map<string, Promise<void>>>();
|
||||
const REFRESH_MS = 6 * 60 * 60 * 1000;
|
||||
|
||||
/** Cached metadata refresh only. Never exchanges tokens or blocks a run/page on a provider. */
|
||||
export function refreshSubscriptionConnection(db: Db, input: SubscriptionConnection, id: string, request: typeof fetch = fetch): Promise<void> {
|
||||
let active = jobs.get(db);
|
||||
if (!active) jobs.set(db, active = new Map());
|
||||
const existing = active.get(id);
|
||||
if (existing) return existing;
|
||||
// Bound provider concurrency across all companies on this instance. Dashboard
|
||||
// discovery waits below; opportunistic run observations remain due when busy.
|
||||
if (active.size >= 4) return Promise.resolve();
|
||||
const task = (async () => {
|
||||
const [claimed] = await db.update(aiSubscriptions).set({ lastCheckedAt: new Date() }).where(and(
|
||||
eq(aiSubscriptions.companyId, input.companyId), eq(aiSubscriptions.id, id),
|
||||
or(isNull(aiSubscriptions.lastCheckedAt), lt(aiSubscriptions.lastCheckedAt, new Date(Date.now() - REFRESH_MS))),
|
||||
)).returning({ id: aiSubscriptions.id });
|
||||
if (!claimed) return;
|
||||
try {
|
||||
const observation = await probeSubscriptionIdentity(input.companyId, input.provider, input.credential, request);
|
||||
// A later execution/reconnect may now use another account. Never replace
|
||||
// that binding with a slow response for the previous credential.
|
||||
const [binding] = await db.select().from(aiSubscriptionConnections).where(and(eq(aiSubscriptionConnections.companyId, input.companyId), eq(aiSubscriptionConnections.grantId, input.grantId)));
|
||||
if (binding?.credentialKey !== observation.credentialKey) return;
|
||||
await subscriptionService(db).register(input, observation);
|
||||
} catch {
|
||||
await db.update(aiSubscriptions).set({ refreshStatus: "unavailable" }).where(and(eq(aiSubscriptions.companyId, input.companyId), eq(aiSubscriptions.id, id)));
|
||||
}
|
||||
})().catch(() => {
|
||||
// No raw provider/credential errors are logged or returned to a user.
|
||||
logger.warn({ companyId: input.companyId, subscriptionId: id }, "Subscription observation could not be saved");
|
||||
}).finally(() => active!.delete(id));
|
||||
active.set(id, task);
|
||||
return task;
|
||||
}
|
||||
|
||||
export function refreshCompanySubscriptions(db: Db, companyId: string, userId: string): Promise<void> {
|
||||
let active = discovery.get(db);
|
||||
if (!active) discovery.set(db, active = new Map());
|
||||
const key = `${companyId}:${userId}`;
|
||||
const existing = active.get(key);
|
||||
if (existing) return existing;
|
||||
if (active.size >= 20) throw tooManyRequests("Subscription account checks are busy. Try again shortly.");
|
||||
const task = (async () => {
|
||||
const service = aiConnectionService(db);
|
||||
// Uses the existing credential audience. Being a company admin does not
|
||||
// authorize probing another member's personal credentials.
|
||||
for (const row of await service.subscriptionAccounts(companyId, userId)) {
|
||||
if (row.summary.status !== "connected") continue;
|
||||
try {
|
||||
const credential = await service.credential(row);
|
||||
const input: SubscriptionConnection = { companyId, connectionId: row.connection.id, grantId: row.grant.id,
|
||||
provider: row.summary.provider, name: row.connection.name, ownerUserId: row.grant.subjectUserId, credential };
|
||||
const id = await subscriptionService(db).register(input);
|
||||
// Accepted discovery must not silently skip an account. At most twenty
|
||||
// discovery tasks can wait here; never create an unbounded provider queue.
|
||||
// Recheck after each completion because another discovery may take a slot.
|
||||
let providers = jobs.get(db);
|
||||
while (providers && providers.size >= 4 && !providers.has(id)) {
|
||||
await Promise.race(providers.values());
|
||||
providers = jobs.get(db);
|
||||
}
|
||||
await refreshSubscriptionConnection(db, input, id);
|
||||
} catch {
|
||||
logger.warn({ companyId, connectionId: row.connection.id }, "Subscription discovery unavailable for a connection");
|
||||
}
|
||||
}
|
||||
})().catch(() => logger.warn({ companyId }, "Subscription discovery unavailable"))
|
||||
.finally(() => active!.delete(key));
|
||||
active.set(key, task);
|
||||
return task;
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import { and, eq, exists, gte, isNull, lte, notExists, or, sql } from "drizzle-orm";
|
||||
import { aiSubscriptions, aiSubscriptionPrices, aiSubscriptionConnections, connectionGrants, connectionGrantMembers, agents, authUsers, companyMemberships, costEvents, type Db } from "@paperclipai/db";
|
||||
import { addCents, monthlySubscriptionCents, type SubscriptionCostReport, type SubscriptionPrice, type SubscriptionUsage } from "@paperclipai/shared";
|
||||
import { withAccountingReadSnapshot } from "./accounting-transaction.js";
|
||||
import { ordinaryInputTokens } from "./costs.js";
|
||||
import { resolveCostDateRange, type CostDateRange } from "./cost-date-range.js";
|
||||
import { canEditSubscription, canonicalSubscriptionId, type SubscriptionActor } from "./subscriptions.js";
|
||||
|
||||
export function emptySubscriptionUsage(): SubscriptionUsage {
|
||||
return { inputTokens: 0, cachedInputTokens: 0, outputTokens: 0, costCents: "0.0000000", eventCount: 0, estimatedEventCount: 0, unpricedEventCount: 0 };
|
||||
}
|
||||
|
||||
function addUsage(target: SubscriptionUsage, source: SubscriptionUsage) {
|
||||
target.costCents = addCents(target.costCents, source.costCents);
|
||||
for (const key of ["inputTokens", "cachedInputTokens", "outputTokens", "eventCount", "estimatedEventCount", "unpricedEventCount"] as const) target[key] += Number(source[key]);
|
||||
}
|
||||
|
||||
function priceDto(price: typeof aiSubscriptionPrices.$inferSelect): SubscriptionPrice {
|
||||
return { revision: price.revision, plan: price.plan, amountCents: price.amountCents,
|
||||
monthlyCents: price.amountCents == null ? null : monthlySubscriptionCents(price.amountCents, price.cadence),
|
||||
currency: price.currency, cadence: price.cadence, status: price.status, source: price.source,
|
||||
sourceUrl: price.sourceUrl, effectiveAt: price.effectiveAt.toISOString() };
|
||||
}
|
||||
|
||||
export async function subscriptionCostReport(db: Db, companyId: string, actor: SubscriptionActor, range?: CostDateRange): Promise<SubscriptionCostReport> {
|
||||
return withAccountingReadSnapshot(db, companyId, async tx => {
|
||||
const period = resolveCostDateRange(range);
|
||||
const conditions = [eq(costEvents.companyId, companyId)];
|
||||
if (period?.from) conditions.push(gte(costEvents.occurredAt, period.from));
|
||||
if (period?.to) conditions.push(lte(costEvents.occurredAt, period.to));
|
||||
// Company cost-read permission covers aggregate run usage, not another
|
||||
// member's private subscription fee. Billing editors retain visibility
|
||||
// after disconnection; other readers need an authorized shared audience.
|
||||
const audience = and(eq(connectionGrantMembers.companyId, companyId), eq(connectionGrantMembers.grantId, connectionGrants.id));
|
||||
const visible = or(
|
||||
sql`${actor.userId} = any(${aiSubscriptions.ownerUserIds})`,
|
||||
actor.canManage ? eq(aiSubscriptions.shared, true) : undefined,
|
||||
exists(tx.select({ id: aiSubscriptionConnections.id }).from(aiSubscriptionConnections)
|
||||
.innerJoin(connectionGrants, and(eq(connectionGrants.id, aiSubscriptionConnections.grantId), eq(connectionGrants.companyId, companyId)))
|
||||
.where(and(eq(aiSubscriptionConnections.companyId, companyId), eq(aiSubscriptionConnections.subscriptionId, aiSubscriptions.id),
|
||||
eq(connectionGrants.kind, "organization"), eq(connectionGrants.status, "active"), or(
|
||||
notExists(tx.select({ id: connectionGrantMembers.id }).from(connectionGrantMembers).where(audience)),
|
||||
exists(tx.select({ id: connectionGrantMembers.id }).from(connectionGrantMembers).where(and(audience,
|
||||
eq(connectionGrantMembers.subjectType, "user"), eq(connectionGrantMembers.subjectId, actor.userId)))),
|
||||
)))),
|
||||
);
|
||||
const visibleCurrent = and(eq(aiSubscriptions.companyId, companyId), isNull(aiSubscriptions.mergedIntoId), visible);
|
||||
const [accounts, links, prices, owners, groups] = await Promise.all([
|
||||
tx.select().from(aiSubscriptions).where(visibleCurrent),
|
||||
// Historical aliases are needed to distinguish hidden accounts from
|
||||
// truly unattributed runs. Do not load their private metadata or prices.
|
||||
tx.select({ id: aiSubscriptions.id, mergedIntoId: aiSubscriptions.mergedIntoId }).from(aiSubscriptions).where(eq(aiSubscriptions.companyId, companyId)),
|
||||
tx.select({ price: aiSubscriptionPrices }).from(aiSubscriptions).innerJoin(aiSubscriptionPrices, and(
|
||||
eq(aiSubscriptionPrices.companyId, aiSubscriptions.companyId), eq(aiSubscriptionPrices.subscriptionId, aiSubscriptions.id),
|
||||
eq(aiSubscriptionPrices.revision, aiSubscriptions.revision),
|
||||
)).where(visibleCurrent),
|
||||
tx.select({ id: authUsers.id, name: authUsers.name }).from(authUsers).innerJoin(companyMemberships, and(
|
||||
eq(companyMemberships.principalId, authUsers.id), eq(companyMemberships.companyId, companyId), eq(companyMemberships.principalType, "user"))),
|
||||
tx.select({ subscriptionId: costEvents.subscriptionId, billingType: costEvents.billingType,
|
||||
agentId: costEvents.agentId, agentName: agents.name,
|
||||
inputTokens: sql<number>`coalesce(sum(${ordinaryInputTokens}), 0)::double precision`,
|
||||
cachedInputTokens: sql<number>`coalesce(sum(${costEvents.cachedInputTokens}), 0)::double precision`,
|
||||
outputTokens: sql<number>`coalesce(sum(${costEvents.outputTokens}), 0)::double precision`,
|
||||
costCents: sql<string>`coalesce(sum(${costEvents.costCents}), 0)::text`,
|
||||
eventCount: sql<number>`count(*)::int`,
|
||||
estimatedEventCount: sql<number>`count(*) filter (where ${costEvents.costStatus} = 'estimated')::int`,
|
||||
unpricedEventCount: sql<number>`count(*) filter (where ${costEvents.costStatus} = 'unpriced' and ${costEvents.billingType} <> 'subscription_included')::int`,
|
||||
}).from(costEvents).leftJoin(agents, and(eq(agents.id, costEvents.agentId), eq(agents.companyId, companyId)))
|
||||
.where(and(...conditions)).groupBy(costEvents.subscriptionId, costEvents.billingType, costEvents.agentId, agents.name),
|
||||
]);
|
||||
const report: SubscriptionCostReport = { canRefresh: !actor.readOnly, asOf: new Date().toISOString(), accounts: [], monthlyTotals: [],
|
||||
activeCount: 0, unknownPriceCount: 0, unidentifiedAccountCount: 0,
|
||||
api: emptySubscriptionUsage(), subscription: emptySubscriptionUsage(), unknown: emptySubscriptionUsage(), unattributedSubscription: emptySubscriptionUsage() };
|
||||
const currentPrices = new Map(prices.map(({ price }) => [price.subscriptionId, priceDto(price)]));
|
||||
const ownerNames = new Map(owners.map(owner => [owner.id, owner.name]));
|
||||
for (const account of accounts) {
|
||||
const price = currentPrices.get(account.id);
|
||||
if (!price) throw new Error("Subscription price history is incomplete");
|
||||
const ownerUserId = !account.shared && account.ownerUserIds.length === 1 ? account.ownerUserIds[0] : null;
|
||||
report.accounts.push({ id: account.id, provider: account.provider,
|
||||
name: account.ownerUserIds.length > 0 && (account.shared || !account.ownerUserIds.includes(actor.userId)) ? `${account.provider} subscription` : account.name,
|
||||
ownerUserId, ownerName: ownerNames.get(ownerUserId ?? "") ?? null, shared: account.shared,
|
||||
identityVerified: account.identityVerified, detectedPlan: account.detectedPlan,
|
||||
observedAt: account.observedAt?.toISOString() ?? null, lastCheckedAt: account.lastCheckedAt?.toISOString() ?? null,
|
||||
refreshStatus: account.refreshStatus, canEdit: canEditSubscription(account, actor), price,
|
||||
usage: emptySubscriptionUsage(), agents: [] });
|
||||
if (price.status !== "active") continue;
|
||||
report.activeCount++;
|
||||
if (!account.identityVerified) report.unidentifiedAccountCount++;
|
||||
if (price.monthlyCents == null) { report.unknownPriceCount++; continue; }
|
||||
let total = report.monthlyTotals.find(row => row.currency === price.currency);
|
||||
if (!total) report.monthlyTotals.push(total = { currency: price.currency, amountCents: "0.0000000", estimatedCount: 0 });
|
||||
total.amountCents = addCents(total.amountCents, price.monthlyCents);
|
||||
if (price.source !== "user") total.estimatedCount++;
|
||||
}
|
||||
const byId = new Map(report.accounts.map(account => [account.id, account]));
|
||||
const aliases = new Map(links.map(account => [account.id, account.mergedIntoId]));
|
||||
const canonicalIds = new Map(links.map(account => [account.id, canonicalSubscriptionId(account.id, aliases)]));
|
||||
for (const group of groups) {
|
||||
const isSubscription = group.billingType === "subscription_included" || group.billingType === "subscription_overage";
|
||||
addUsage(group.billingType === "metered_api" ? report.api : isSubscription ? report.subscription : report.unknown, group);
|
||||
if (!isSubscription) continue;
|
||||
const canonicalId = group.subscriptionId ? canonicalIds.get(group.subscriptionId) : undefined;
|
||||
const account = canonicalId ? byId.get(canonicalId) : undefined;
|
||||
if (canonicalId && !account) continue; // Known private account; not missing attribution.
|
||||
if (!account) { addUsage(report.unattributedSubscription, group); continue; }
|
||||
addUsage(account.usage, group);
|
||||
if (group.agentId && !account.agents.some(agent => agent.id === group.agentId)) account.agents.push({ id: group.agentId, name: group.agentName ?? "Agent" });
|
||||
}
|
||||
report.accounts.sort((a, b) => (a.ownerName ?? "Shared").localeCompare(b.ownerName ?? "Shared") || a.name.localeCompare(b.name));
|
||||
report.monthlyTotals.sort((a, b) => a.currency.localeCompare(b.currency));
|
||||
return report;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
import { and, eq, inArray, sql } from "drizzle-orm";
|
||||
import { aiSubscriptions, aiSubscriptionPrices, aiSubscriptionConnections, connectionGrants, toolConnections, type Db } from "@paperclipai/db";
|
||||
import { aiConnectionMetadataSchema, normalizeCents, subscriptionPlan, type AiProvider, type UpdateSubscriptionPrice } from "@paperclipai/shared";
|
||||
import { conflict, forbidden, notFound } from "../errors.js";
|
||||
import { logActivity, type ActivityPublication } from "./activity-log.js";
|
||||
import { publishAccountingActivities } from "./accounting-transaction.js";
|
||||
import { subscriptionCredentialIdentity, subscriptionIdentityKey, type SubscriptionIdentity } from "./subscription-identity.js";
|
||||
|
||||
type Account = typeof aiSubscriptions.$inferSelect;
|
||||
type Price = typeof aiSubscriptionPrices.$inferInsert;
|
||||
export interface SubscriptionActor { userId: string; canManage: boolean; readOnly?: boolean }
|
||||
export interface SubscriptionConnection {
|
||||
companyId: string; connectionId: string; grantId: string; provider: AiProvider;
|
||||
name: string; ownerUserId: string | null; credential: string;
|
||||
}
|
||||
|
||||
export function canonicalSubscriptionId(id: string, accounts: Pick<Account, "id" | "mergedIntoId">[] | Map<string, string | null>): string {
|
||||
const map = accounts instanceof Map ? accounts : new Map(accounts.map(row => [row.id, row.mergedIntoId]));
|
||||
const seen = new Set<string>();
|
||||
while (map.get(id)) {
|
||||
if (seen.has(id)) throw new Error("Subscription link cycle");
|
||||
seen.add(id); id = map.get(id)!;
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
function detectedPrice(companyId: string, subscriptionId: string, plan: string | null, revision: number): Price {
|
||||
return { companyId, subscriptionId, revision, plan: plan ?? "Plan unknown", amountCents: null, source: "unknown" };
|
||||
}
|
||||
|
||||
function autoPrice(account: Pick<Account, "id" | "companyId" | "provider" | "identityVerified">, plan: string | null, revision: number): Price {
|
||||
// A plan hint alone cannot prove whether two rotated credentials are one paid
|
||||
// seat. Require a stable identity before adding an automatic fee to totals.
|
||||
const catalog = account.identityVerified ? subscriptionPlan(account.provider, plan) : null;
|
||||
return { ...detectedPrice(account.companyId, account.id, plan, revision),
|
||||
...(catalog ? { plan: catalog.name, amountCents: normalizeCents(catalog.monthlyCents), currency: catalog.currency, source: "catalog" as const, sourceUrl: catalog.sourceUrl } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
async function lock(db: Db, companyId: string) {
|
||||
// A separate, short lock; no provider requests or credential rotation under it.
|
||||
await db.execute(sql`select pg_advisory_xact_lock(hashtext('subscription_costs'), hashtext(${companyId}))`);
|
||||
}
|
||||
|
||||
async function withSubscriptionTransaction<T>(db: Db, companyId: string, work: (tx: Db, publications: ActivityPublication[]) => Promise<T>) {
|
||||
const publications: ActivityPublication[] = [];
|
||||
const result = await db.transaction(async transaction => {
|
||||
const tx = transaction as unknown as Db;
|
||||
await lock(tx, companyId);
|
||||
return work(tx, publications);
|
||||
});
|
||||
publishAccountingActivities(companyId, publications);
|
||||
return result;
|
||||
}
|
||||
|
||||
type Ownership = Pick<Account, "ownerUserIds" | "shared">;
|
||||
function combineOwnership(a: Ownership, b: Ownership): Ownership {
|
||||
return { ownerUserIds: [...new Set([...a.ownerUserIds, ...b.ownerUserIds])].sort(), shared: a.shared || b.shared };
|
||||
}
|
||||
|
||||
export function canEditSubscription(account: Ownership, actor: SubscriptionActor) {
|
||||
return !actor.readOnly && (account.ownerUserIds.includes(actor.userId) || (account.shared && actor.canManage));
|
||||
}
|
||||
|
||||
async function mergeInTransaction(db: Db, companyId: string, source: Account, target: Account, automatic: boolean) {
|
||||
if (source.id === target.id) throw conflict("Choose a different subscription to link");
|
||||
if (source.provider !== target.provider || source.mergedIntoId || target.mergedIntoId) throw conflict("Choose two current accounts from the same provider");
|
||||
await db.update(aiSubscriptions).set(combineOwnership(source, target)).where(and(eq(aiSubscriptions.id, target.id), eq(aiSubscriptions.companyId, companyId)));
|
||||
const prices = await db.select().from(aiSubscriptionPrices).where(and(eq(aiSubscriptionPrices.companyId, companyId), inArray(aiSubscriptionPrices.subscriptionId, [source.id, target.id])));
|
||||
const sourcePrice = prices.find(row => row.subscriptionId === source.id && row.revision === source.revision)!;
|
||||
const targetPrice = prices.find(row => row.subscriptionId === target.id && row.revision === target.revision)!;
|
||||
if (automatic && sourcePrice.source === "user") {
|
||||
if (targetPrice.source === "user" && ["amountCents", "currency", "cadence", "status"].some(key => sourcePrice[key as keyof typeof sourcePrice] !== targetPrice[key as keyof typeof targetPrice])) {
|
||||
throw conflict("These accounts have different saved prices. Link them after choosing the price to keep.");
|
||||
}
|
||||
if (targetPrice.source !== "user") {
|
||||
await db.insert(aiSubscriptionPrices).values({ ...sourcePrice, id: undefined, subscriptionId: target.id, revision: target.revision + 1, effectiveAt: new Date() });
|
||||
await db.update(aiSubscriptions).set({ revision: target.revision + 1 }).where(eq(aiSubscriptions.id, target.id));
|
||||
}
|
||||
}
|
||||
await db.update(aiSubscriptions).set({ mergedIntoId: target.id, revision: source.revision + 1 }).where(and(eq(aiSubscriptions.id, source.id), eq(aiSubscriptions.companyId, companyId)));
|
||||
// Preserve each old ID for historical run attribution. Flatten existing links.
|
||||
await db.update(aiSubscriptions).set({ mergedIntoId: target.id }).where(and(eq(aiSubscriptions.companyId, companyId), eq(aiSubscriptions.mergedIntoId, source.id)));
|
||||
await db.update(aiSubscriptionConnections).set({ subscriptionId: target.id }).where(and(eq(aiSubscriptionConnections.companyId, companyId), eq(aiSubscriptionConnections.subscriptionId, source.id)));
|
||||
return target.id;
|
||||
}
|
||||
|
||||
export function subscriptionService(db: Db) {
|
||||
async function register(input: SubscriptionConnection, observed?: SubscriptionIdentity) {
|
||||
const identity = { ...(observed ?? subscriptionCredentialIdentity(input.companyId, input.provider, input.credential)) };
|
||||
// Only a successful provider observation may match another grant's billing
|
||||
// identity or add its editors. Provisional rows are grant-scoped, even when
|
||||
// two callers supply the same unverified credential or forged ID claims.
|
||||
if (!observed?.verified) identity.accountKey = subscriptionIdentityKey(input.companyId, input.provider, ["grant", input.grantId, identity.credentialKey]);
|
||||
if (!observed) {
|
||||
const [cached] = await db.select().from(aiSubscriptionConnections).where(and(eq(aiSubscriptionConnections.companyId, input.companyId), eq(aiSubscriptionConnections.grantId, input.grantId)));
|
||||
if (cached?.credentialKey === identity.credentialKey && cached.connectionId === input.connectionId) return cached.subscriptionId;
|
||||
}
|
||||
return withSubscriptionTransaction(db, input.companyId, async (tx, publications) => {
|
||||
// Company and grant identity are authoritative, even for internal callers.
|
||||
const [grant] = await tx.select({ grant: connectionGrants, connection: toolConnections }).from(connectionGrants)
|
||||
.innerJoin(toolConnections, and(eq(toolConnections.id, connectionGrants.connectionId), eq(toolConnections.companyId, connectionGrants.companyId)))
|
||||
.where(and(eq(connectionGrants.companyId, input.companyId), eq(connectionGrants.id, input.grantId), eq(toolConnections.id, input.connectionId)));
|
||||
const metadata = aiConnectionMetadataSchema.safeParse(grant?.connection.config.ai);
|
||||
if (!grant || grant.grant.status !== "active" || grant.connection.connectionPurpose !== "ai"
|
||||
|| !grant.connection.enabled || grant.connection.status !== "active"
|
||||
|| !metadata.success || metadata.data.method !== "subscription" || metadata.data.provider !== input.provider) {
|
||||
throw notFound("Subscription connection not found");
|
||||
}
|
||||
const [binding] = await tx.select().from(aiSubscriptionConnections).where(and(eq(aiSubscriptionConnections.companyId, input.companyId), eq(aiSubscriptionConnections.grantId, input.grantId)));
|
||||
const accounts = await tx.select().from(aiSubscriptions).where(eq(aiSubscriptions.companyId, input.companyId));
|
||||
if (observed && binding && binding.credentialKey !== identity.credentialKey) return canonicalSubscriptionId(binding.subscriptionId, accounts);
|
||||
// A fresh credential-local hint cannot override a verified profile binding.
|
||||
if (!observed && binding?.credentialKey === identity.credentialKey) return canonicalSubscriptionId(binding.subscriptionId, accounts);
|
||||
const known = accounts.find(row => row.provider === input.provider && row.accountKey === identity.accountKey);
|
||||
let account = known ? accounts.find(row => row.id === canonicalSubscriptionId(known.id, accounts))! : undefined;
|
||||
const previous = binding?.credentialKey === identity.credentialKey ? accounts.find(row => row.id === canonicalSubscriptionId(binding.subscriptionId, accounts)) : undefined;
|
||||
if (!account && previous && observed && !previous.identityVerified && !previous.mergedIntoId) {
|
||||
[account] = await tx.update(aiSubscriptions).set({ accountKey: identity.accountKey, identityVerified: identity.verified }).where(eq(aiSubscriptions.id, previous.id)).returning();
|
||||
}
|
||||
if (!account) {
|
||||
[account] = await tx.insert(aiSubscriptions).values({ companyId: input.companyId, provider: input.provider,
|
||||
accountKey: identity.accountKey, identityVerified: identity.verified, name: grant.connection.name,
|
||||
ownerUserIds: grant.grant.subjectUserId ? [grant.grant.subjectUserId] : [], shared: grant.grant.kind === "organization", detectedPlan: identity.plan,
|
||||
}).returning();
|
||||
await tx.insert(aiSubscriptionPrices).values(autoPrice(account, identity.plan, 0));
|
||||
await logActivity(tx, { companyId: input.companyId, actorType: "system", actorId: "subscription_reporting",
|
||||
action: "subscription.discovered", entityType: "ai_subscription", entityId: account.id, details: { provider: input.provider } }, publications);
|
||||
}
|
||||
// The union is independent of discovery order. Credential sharing does
|
||||
// not transfer personal ownership, and personal reuse does not remove
|
||||
// managers' authority over a fee already connected to the company.
|
||||
const ownership = combineOwnership(account, {
|
||||
ownerUserIds: grant.grant.subjectUserId ? [grant.grant.subjectUserId] : [], shared: grant.grant.kind === "organization",
|
||||
});
|
||||
if (ownership.shared !== account.shared || ownership.ownerUserIds.join() !== account.ownerUserIds.join()) {
|
||||
[account] = await tx.update(aiSubscriptions).set(ownership).where(eq(aiSubscriptions.id, account.id)).returning();
|
||||
await logActivity(tx, { companyId: input.companyId, actorType: "system", actorId: "subscription_reporting",
|
||||
action: "subscription.ownership_updated", entityType: "ai_subscription", entityId: account.id,
|
||||
details: { shared: ownership.shared, ownerCount: ownership.ownerUserIds.length } }, publications);
|
||||
}
|
||||
if (observed && previous && previous.id !== account.id && !previous.identityVerified) {
|
||||
await mergeInTransaction(tx, input.companyId, previous, account, true);
|
||||
await logActivity(tx, { companyId: input.companyId, actorType: "system", actorId: "subscription_reporting",
|
||||
action: "subscription.linked", entityType: "ai_subscription", entityId: previous.id, details: { targetId: account.id, automatic: true } }, publications);
|
||||
// Merging can adopt a user price and advance the revision.
|
||||
[account] = await tx.select().from(aiSubscriptions).where(eq(aiSubscriptions.id, account.id));
|
||||
}
|
||||
if (observed) {
|
||||
if (identity.plan) {
|
||||
const [price] = await tx.select().from(aiSubscriptionPrices).where(and(eq(aiSubscriptionPrices.subscriptionId, account.id), eq(aiSubscriptionPrices.revision, account.revision)));
|
||||
const next = autoPrice(account, identity.plan, account.revision + 1);
|
||||
if (price?.source !== "user" && (price?.plan !== next.plan || price?.amountCents !== (next.amountCents ?? null) || price?.source !== next.source)) {
|
||||
account.revision++;
|
||||
await tx.insert(aiSubscriptionPrices).values(next);
|
||||
}
|
||||
}
|
||||
await tx.update(aiSubscriptions).set({ detectedPlan: identity.plan ?? account.detectedPlan, observedAt: identity.plan ? new Date() : account.observedAt,
|
||||
lastCheckedAt: new Date(), refreshStatus: identity.plan ? "ok" : "unavailable", revision: account.revision }).where(eq(aiSubscriptions.id, account.id));
|
||||
}
|
||||
await tx.insert(aiSubscriptionConnections).values({ companyId: input.companyId, connectionId: input.connectionId, grantId: input.grantId,
|
||||
credentialKey: identity.credentialKey, subscriptionId: account.id }).onConflictDoUpdate({ target: [aiSubscriptionConnections.companyId, aiSubscriptionConnections.grantId],
|
||||
set: { credentialKey: identity.credentialKey, subscriptionId: account.id } });
|
||||
return account.id;
|
||||
});
|
||||
}
|
||||
|
||||
async function updatePrice(companyId: string, id: string, input: UpdateSubscriptionPrice, actor: SubscriptionActor) {
|
||||
return withSubscriptionTransaction(db, companyId, async (tx, publications) => {
|
||||
const [account] = await tx.select().from(aiSubscriptions).where(and(eq(aiSubscriptions.companyId, companyId), eq(aiSubscriptions.id, id)));
|
||||
if (!account) throw notFound("Subscription not found");
|
||||
if (!canEditSubscription(account, actor)) throw forbidden("Only subscription owners or managers of shared accounts can edit prices");
|
||||
if (account.mergedIntoId || account.revision !== input.expectedRevision) throw conflict("This subscription changed. Reload it before saving.");
|
||||
const revision = account.revision + 1;
|
||||
await tx.insert(aiSubscriptionPrices).values({ companyId, subscriptionId: id, revision, plan: input.plan,
|
||||
amountCents: input.amountCents == null ? null : normalizeCents(input.amountCents), currency: input.currency,
|
||||
cadence: input.cadence, status: input.status, source: "user" });
|
||||
await tx.update(aiSubscriptions).set({ revision }).where(eq(aiSubscriptions.id, id));
|
||||
await logActivity(tx, { companyId, actorType: "user", actorId: actor.userId, action: "subscription.price_updated",
|
||||
entityType: "ai_subscription", entityId: id, details: { revision, status: input.status } }, publications);
|
||||
return { id, revision };
|
||||
});
|
||||
}
|
||||
|
||||
async function merge(companyId: string, id: string, targetId: string, expectedRevision: number, targetRevision: number, actor: SubscriptionActor) {
|
||||
return withSubscriptionTransaction(db, companyId, async (tx, publications) => {
|
||||
const rows = await tx.select().from(aiSubscriptions).where(and(eq(aiSubscriptions.companyId, companyId), inArray(aiSubscriptions.id, [id, targetId])));
|
||||
const source = rows.find(row => row.id === id), target = rows.find(row => row.id === targetId);
|
||||
if (!source || !target) throw notFound("Subscription not found");
|
||||
if (!canEditSubscription(source, actor) || !canEditSubscription(target, actor)) throw forbidden("You must be able to edit both subscriptions");
|
||||
if (source.revision !== expectedRevision || target.revision !== targetRevision) throw conflict("These subscriptions changed. Reload before linking them.");
|
||||
const result = await mergeInTransaction(tx, companyId, source, target, false);
|
||||
await logActivity(tx, { companyId, actorType: "user", actorId: actor.userId, action: "subscription.linked", entityType: "ai_subscription", entityId: id, details: { targetId } }, publications);
|
||||
return { id: result };
|
||||
});
|
||||
}
|
||||
return { register, updatePrice, merge };
|
||||
}
|
||||
@@ -43,6 +43,24 @@ afterEach(() => {
|
||||
});
|
||||
|
||||
describe("tenant-session recovery", () => {
|
||||
it("loads anonymous Dot consent despite concurrent protected background probes", async () => {
|
||||
const reload = vi.fn();
|
||||
const requestId = `pcmcp_request_${"a".repeat(43)}`;
|
||||
const recovery = createTenantSessionRecoveryCoordinator(reload, () => `/dot-connect/${requestId}`);
|
||||
vi.spyOn(tenantSessionRecovery, "recoverIfNeeded").mockImplementation(recovery.recoverIfNeeded);
|
||||
fetchMock.mockImplementation((url: string) => Promise.resolve(
|
||||
url.includes("/dot-mcp/requests/")
|
||||
? jsonResponse({ id: requestId, agentConnection: true })
|
||||
: errorResponse({ error: "tenant_session_required" }),
|
||||
));
|
||||
|
||||
const background = api.get("/health");
|
||||
const consent = api.get(`/dot-mcp/requests/${requestId}`);
|
||||
await expect(background).rejects.toMatchObject({ status: 401 });
|
||||
await expect(consent).resolves.toEqual({ id: requestId, agentConnection: true });
|
||||
expect(reload).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps concurrent failures pending and schedules one top-level reload", async () => {
|
||||
const reload = vi.fn();
|
||||
const recovery = createTenantSessionRecoveryCoordinator(reload);
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import type { SubscriptionCostReport, UpdateSubscriptionPrice } from "@paperclipai/shared";
|
||||
import { api } from "./client";
|
||||
|
||||
export const subscriptionsApi = {
|
||||
report(companyId: string, from?: string, to?: string) {
|
||||
const query = new URLSearchParams();
|
||||
if (from) query.set("from", from);
|
||||
if (to) query.set("to", to);
|
||||
if (!from && !to) query.set("period", "all");
|
||||
return api.get<SubscriptionCostReport>(`/companies/${companyId}/costs/subscriptions?${query}`);
|
||||
},
|
||||
refresh: (companyId: string) => api.post<{ status: string }>(`/companies/${companyId}/costs/subscriptions/refresh`, {}),
|
||||
update: (companyId: string, id: string, input: UpdateSubscriptionPrice) =>
|
||||
api.patch(`/companies/${companyId}/costs/subscriptions/${id}`, input),
|
||||
link: (companyId: string, id: string, targetId: string, expectedRevision: number, targetRevision: number) =>
|
||||
api.post(`/companies/${companyId}/costs/subscriptions/${id}/link`, { targetId, expectedRevision, targetRevision }),
|
||||
};
|
||||
@@ -0,0 +1,26 @@
|
||||
import type { ReactNode } from "react";
|
||||
import type { CostByAgent } from "@paperclipai/shared";
|
||||
import { formatCents } from "../lib/utils";
|
||||
import { CostEstimateLabel } from "./CostEstimateLabel";
|
||||
|
||||
export function CostAmount({
|
||||
costCents,
|
||||
eventCount,
|
||||
estimatedEventCount,
|
||||
unpricedEventCount,
|
||||
suffix,
|
||||
}: Pick<CostByAgent, "costCents"> & Partial<Pick<CostByAgent, "eventCount" | "estimatedEventCount">> & {
|
||||
unpricedEventCount?: number;
|
||||
suffix?: ReactNode;
|
||||
}) {
|
||||
const entirelyUnpriced = costCents === 0 && (eventCount ?? 0) > 0 && unpricedEventCount === eventCount;
|
||||
return (
|
||||
<div className="flex flex-col items-end gap-1 text-right">
|
||||
<div className="whitespace-nowrap font-mono font-medium tabular-nums">
|
||||
{entirelyUnpriced ? "—" : formatCents(costCents)}
|
||||
{suffix}
|
||||
</div>
|
||||
<CostEstimateLabel eventCount={eventCount} estimatedEventCount={estimatedEventCount} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
import type { CostByUserReport } from "@paperclipai/shared";
|
||||
import { CostEstimateLabel } from "./CostEstimateLabel";
|
||||
import { CostAmount } from "./CostAmount";
|
||||
import { Identity } from "./Identity";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
|
||||
import { formatCents, formatTokens } from "../lib/utils";
|
||||
import { formatTokens } from "../lib/utils";
|
||||
|
||||
export function CostByUserTable({ report }: { report: CostByUserReport }) {
|
||||
return (
|
||||
@@ -38,8 +38,7 @@ export function CostByUserTable({ report }: { report: CostByUserReport }) {
|
||||
</td>
|
||||
<td className="px-4 py-3 text-right tabular-nums">{formatTokens(row.outputTokens)}</td>
|
||||
<td className="py-3 pl-4 text-right tabular-nums">
|
||||
<div>{row.costCents === 0 && row.eventCount > 0 && row.unpricedEventCount === row.eventCount ? "—" : formatCents(row.costCents)}</div>
|
||||
<CostEstimateLabel eventCount={row.eventCount} estimatedEventCount={row.estimatedEventCount} />
|
||||
<CostAmount costCents={row.costCents} eventCount={row.eventCount} estimatedEventCount={row.estimatedEventCount} unpricedEventCount={row.unpricedEventCount} />
|
||||
{row.unpricedEventCount > 0 && <div className="whitespace-nowrap text-xs text-muted-foreground">{row.unpricedEventCount} unpriced {row.unpricedEventCount === 1 ? "charge" : "charges"}</div>}
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@@ -221,7 +221,7 @@ it.each([{ enableOpenAiDot: false, enablePublicMcp: true }, { enableOpenAiDot: t
|
||||
});
|
||||
|
||||
it("copies one scoped Dot prompt, resumes on Back, and trusts only server readiness", async () => {
|
||||
const connection = { enabled: true, resourceUrl: "https://paperclip.example/mcp/runner", agentStatus: "idle", binding: null as any };
|
||||
const connection = { enabled: true, resourceUrl: "https://paperclip.example/mcp/runner", agentStatus: "idle", agentLifecycleState: "ready", canConfigureConnection: true, binding: null as any };
|
||||
dotApi.create.mockResolvedValue({ agent: { id: "dot-agent", status: "idle" }, approvalId: null, binding: null });
|
||||
dotApi.connection.mockImplementation(async () => ({ ...connection }));
|
||||
dotApi.pair.mockImplementation(async () => {
|
||||
@@ -265,7 +265,7 @@ it("copies one scoped Dot prompt, resumes on Back, and trusts only server readin
|
||||
|
||||
it("waits for company approval before issuing a Dot capability", async () => {
|
||||
dotApi.create.mockResolvedValue({ agent: { id: "pending-dot", status: "pending_approval" }, approvalId: "approval-id", binding: null });
|
||||
dotApi.connection.mockResolvedValue({ enabled: true, resourceUrl: "https://paperclip.example/mcp/runner", agentStatus: "pending_approval", binding: null });
|
||||
dotApi.connection.mockResolvedValue({ enabled: true, resourceUrl: "https://paperclip.example/mcp/runner", agentStatus: "pending_approval", agentLifecycleState: "pending_approval", canConfigureConnection: false, binding: null });
|
||||
await act(async () => cache.setQueryData(queryKeys.instance.experimentalSettings, { enableOpenAiDot: true, enablePublicMcp: true }));
|
||||
await click("Invite an external agent");
|
||||
await act(async () => [...document.querySelectorAll("button")].find(b => b.textContent?.startsWith("Dot"))!.click());
|
||||
@@ -298,7 +298,7 @@ const pendingDotBinding = (id: string, expiresAt: string) => ({
|
||||
});
|
||||
|
||||
it.each(["expired", "unavailable"])("automatically replaces an %s saved Dot prompt on opening", async condition => {
|
||||
const connection = { enabled: true, resourceUrl: "https://paperclip.example/mcp/runner", agentStatus: "idle",
|
||||
const connection = { enabled: true, resourceUrl: "https://paperclip.example/mcp/runner", agentStatus: "idle", agentLifecycleState: "ready", canConfigureConnection: true,
|
||||
binding: pendingDotBinding("saved-binding", new Date(Date.now() + (condition === "expired" ? -60000 : 900000)).toISOString()) };
|
||||
dotApi.create.mockResolvedValue({ agent: { id: "dot-agent", status: "idle" }, approvalId: null, binding: connection.binding });
|
||||
dotApi.connection.mockImplementation(async () => ({ ...connection }));
|
||||
@@ -318,7 +318,7 @@ it.each(["expired", "unavailable"])("automatically replaces an %s saved Dot prom
|
||||
});
|
||||
|
||||
it("renews a Dot prompt that expires while setup stays open", async () => {
|
||||
const connection = { enabled: true, resourceUrl: "https://paperclip.example/mcp/runner", agentStatus: "idle", binding: null as any };
|
||||
const connection = { enabled: true, resourceUrl: "https://paperclip.example/mcp/runner", agentStatus: "idle", agentLifecycleState: "ready", canConfigureConnection: true, binding: null as any };
|
||||
dotApi.create.mockResolvedValue({ agent: { id: "dot-agent", status: "idle" }, approvalId: null, binding: null });
|
||||
dotApi.connection.mockImplementation(async () => ({ ...connection }));
|
||||
let generation = 0;
|
||||
@@ -342,10 +342,10 @@ it("renews a Dot prompt that expires while setup stays open", async () => {
|
||||
it("checks fresh connection state before renewing a cached pending Dot invitation", async () => {
|
||||
const staleBinding = pendingDotBinding("saved-binding", new Date(Date.now() - 60000).toISOString());
|
||||
cache.setQueryData(["dot-binding", "company-1", "dot-agent"], {
|
||||
enabled: true, resourceUrl: "https://paperclip.example/mcp/runner", agentStatus: "idle", binding: staleBinding,
|
||||
enabled: true, resourceUrl: "https://paperclip.example/mcp/runner", agentStatus: "idle", agentLifecycleState: "ready", canConfigureConnection: true, binding: staleBinding,
|
||||
});
|
||||
dotApi.create.mockResolvedValue({ agent: { id: "dot-agent", status: "idle" }, approvalId: null, binding: staleBinding });
|
||||
dotApi.connection.mockResolvedValue({ enabled: true, resourceUrl: "https://paperclip.example/mcp/runner", agentStatus: "idle",
|
||||
dotApi.connection.mockResolvedValue({ enabled: true, resourceUrl: "https://paperclip.example/mcp/runner", agentStatus: "idle", agentLifecycleState: "ready", canConfigureConnection: true,
|
||||
binding: { ...staleBinding, status: "ready", connected: true, subscriptionVerified: true } });
|
||||
await openDotSetup();
|
||||
expect(dotApi.connection).toHaveBeenCalled();
|
||||
@@ -354,7 +354,7 @@ it("checks fresh connection state before renewing a cached pending Dot invitatio
|
||||
});
|
||||
|
||||
it("offers a retry after automatic renewal fails without rotating on every poll", async () => {
|
||||
const connection = { enabled: true, resourceUrl: "https://paperclip.example/mcp/runner", agentStatus: "idle",
|
||||
const connection = { enabled: true, resourceUrl: "https://paperclip.example/mcp/runner", agentStatus: "idle", agentLifecycleState: "ready", canConfigureConnection: true,
|
||||
binding: pendingDotBinding("saved-binding", new Date(Date.now() - 60000).toISOString()) };
|
||||
dotApi.create.mockResolvedValue({ agent: { id: "dot-agent", status: "idle" }, approvalId: null, binding: connection.binding });
|
||||
dotApi.connection.mockImplementation(async () => ({ ...connection }));
|
||||
@@ -378,7 +378,7 @@ it("offers a retry after automatic renewal fails without rotating on every poll"
|
||||
|
||||
|
||||
it("does not let an older window renew another window's fresh Dot prompt", async () => {
|
||||
const connection = { enabled: true, resourceUrl: "https://paperclip.example/mcp/runner", agentStatus: "idle", binding: null as any };
|
||||
const connection = { enabled: true, resourceUrl: "https://paperclip.example/mcp/runner", agentStatus: "idle", agentLifecycleState: "ready", canConfigureConnection: true, binding: null as any };
|
||||
dotApi.create.mockResolvedValue({ agent: { id: "dot-agent", status: "idle" }, approvalId: null, binding: null });
|
||||
dotApi.connection.mockImplementation(async () => ({ ...connection }));
|
||||
dotApi.pair.mockImplementation(async () => {
|
||||
@@ -396,7 +396,7 @@ it("does not let an older window renew another window's fresh Dot prompt", async
|
||||
});
|
||||
|
||||
it("retries the event test after Dot connects during a failed prompt renewal", async () => {
|
||||
const connection = { enabled: true, resourceUrl: "https://paperclip.example/mcp/runner", agentStatus: "idle",
|
||||
const connection = { enabled: true, resourceUrl: "https://paperclip.example/mcp/runner", agentStatus: "idle", agentLifecycleState: "ready", canConfigureConnection: true,
|
||||
binding: pendingDotBinding("saved-binding", new Date(Date.now() - 60000).toISOString()) as any };
|
||||
dotApi.create.mockResolvedValue({ agent: { id: "dot-agent", status: "idle" }, approvalId: null, binding: connection.binding });
|
||||
dotApi.connection.mockImplementation(async () => ({ ...connection }));
|
||||
@@ -411,3 +411,71 @@ it("retries the event test after Dot connects during a failed prompt renewal", a
|
||||
expect(dotApi.retry).toHaveBeenCalledExactlyOnceWith("company-1", "dot-agent", "saved-binding");
|
||||
expect(dotApi.pair).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
|
||||
it.each(["preparing", "verifying"])("prepares the Dot prompt while the hire is %s", async agentLifecycleState => {
|
||||
const connection = { enabled: true, resourceUrl: "https://paperclip.example/mcp/runner", agentStatus: "paused",
|
||||
agentLifecycleState, canConfigureConnection: true, binding: null as any };
|
||||
dotApi.create.mockResolvedValue({ agent: { id: "dot-agent", status: "paused" }, approvalId: null, binding: null });
|
||||
dotApi.connection.mockImplementation(async () => ({ ...connection }));
|
||||
dotApi.pair.mockImplementation(async () => {
|
||||
connection.binding = pendingDotBinding("binding", new Date(Date.now() + 900000).toISOString());
|
||||
return { bindingId: "binding", pairingCode: "setup-hire-code", expiresAt: connection.binding.pairingExpiresAt };
|
||||
});
|
||||
await openDotSetup();
|
||||
expect(dotApi.pair).toHaveBeenCalledTimes(1);
|
||||
expect(document.body.textContent).not.toContain("Resume this agent");
|
||||
await click("Copy setup prompt");
|
||||
expect(invites.copy.mock.calls[0][0]).toContain("setup-hire-code");
|
||||
});
|
||||
|
||||
it("does not prepare a Dot capability for a real paused agent", async () => {
|
||||
dotApi.create.mockResolvedValue({ agent: { id: "dot-agent", status: "paused" }, approvalId: null, binding: null });
|
||||
dotApi.connection.mockResolvedValue({ enabled: true, resourceUrl: "https://paperclip.example/mcp/runner",
|
||||
agentStatus: "paused", agentLifecycleState: "paused", canConfigureConnection: false, binding: null });
|
||||
await openDotSetup();
|
||||
expect(dotApi.pair).not.toHaveBeenCalled();
|
||||
expect(document.body.textContent).toContain("Resume this agent before connecting Dot.");
|
||||
});
|
||||
|
||||
it("keeps watching after the event check until hire verification completes", async () => {
|
||||
const connection = { enabled: true, resourceUrl: "https://paperclip.example/mcp/runner", agentStatus: "paused",
|
||||
agentLifecycleState: "verifying", canConfigureConnection: true, binding: null as any };
|
||||
dotApi.create.mockResolvedValue({ agent: { id: "dot-agent", status: "paused" }, approvalId: null, binding: null });
|
||||
dotApi.connection.mockImplementation(async () => ({ ...connection }));
|
||||
dotApi.pair.mockImplementation(async () => {
|
||||
connection.binding = pendingDotBinding("binding", new Date(Date.now() + 900000).toISOString());
|
||||
return { bindingId: "binding", pairingCode: "setup-hire-code", expiresAt: connection.binding.pairingExpiresAt };
|
||||
});
|
||||
await openDotSetup();
|
||||
connection.binding = { ...connection.binding, status: "ready", connected: true, subscriptionVerified: true, hasPendingChallenge: false };
|
||||
await act(async () => cache.invalidateQueries({ queryKey: ["dot-binding", "company-1", "dot-agent"] }));
|
||||
await act(async () => { await new Promise(resolve => setTimeout(resolve, 20)); });
|
||||
expect(document.body.textContent).not.toContain("Your Dot is connected");
|
||||
expect(document.body.textContent).toContain("Test event confirmed: complete");
|
||||
expect(document.body.textContent).toContain("Your Dot confirmed the test event. Paperclip is finishing agent setup.");
|
||||
const finishing = Array.from(document.querySelectorAll("button")).find(button => button.textContent?.includes("Finishing setup…"));
|
||||
expect(finishing?.disabled).toBe(true);
|
||||
connection.agentLifecycleState = "ready";
|
||||
connection.agentStatus = "idle";
|
||||
await act(async () => { await new Promise(resolve => setTimeout(resolve, 2750)); });
|
||||
expect(document.body.textContent).toContain("Your Dot is connected");
|
||||
await click("Done");
|
||||
expect(state.close).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("keeps completed checks but shows a pause blocker for a paired paused Dot", async () => {
|
||||
dotApi.create.mockResolvedValue({ agent: { id: "dot-agent", status: "paused" }, approvalId: null, binding: null });
|
||||
dotApi.connection.mockResolvedValue({ enabled: true, resourceUrl: "https://paperclip.example/mcp/runner",
|
||||
agentStatus: "paused", agentLifecycleState: "paused", canConfigureConnection: false,
|
||||
binding: { ...pendingDotBinding("binding", new Date(Date.now() + 900000).toISOString()),
|
||||
status: "ready", connected: true, subscriptionVerified: true, hasPendingChallenge: false } });
|
||||
await openDotSetup();
|
||||
expect(document.body.textContent).toContain("Test event confirmed: complete");
|
||||
expect(document.body.textContent).toContain("Resume this agent before connecting Dot.");
|
||||
expect(document.body.textContent).not.toContain("Finishing setup…");
|
||||
expect(document.body.textContent).not.toContain("Paperclip is finishing agent setup.");
|
||||
const blocked = Array.from(document.querySelectorAll("button")).find(button => button.textContent?.includes("Agent unavailable"));
|
||||
expect(blocked?.disabled).toBe(true);
|
||||
expect(dotApi.pair).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -0,0 +1,135 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { SubscriptionCostReport } from "@paperclipai/shared";
|
||||
import { SubscriptionCostCard } from "./SubscriptionCostCard";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ update: vi.fn(), link: vi.fn() }));
|
||||
vi.mock("../api/subscriptions", () => ({ subscriptionsApi: mocks }));
|
||||
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
const emptyUsage = () => ({ inputTokens: 0, cachedInputTokens: 0, outputTokens: 0, costCents: "0", eventCount: 0, estimatedEventCount: 0, unpricedEventCount: 0 });
|
||||
function fixture(): SubscriptionCostReport {
|
||||
const price = { revision: 0, plan: "Claude Max 5x", amountCents: "10000", monthlyCents: "10000", currency: "USD", cadence: "month" as const, status: "active" as const, source: "catalog" as const, sourceUrl: "https://claude.com/pricing", effectiveAt: "2026-10-08T00:00:00Z" };
|
||||
return { canRefresh: true, asOf: "2026-10-08T00:00:00Z", activeCount: 1, unknownPriceCount: 0, unidentifiedAccountCount: 0,
|
||||
monthlyTotals: [{ currency: "USD", amountCents: "10000", estimatedCount: 1 }],
|
||||
api: emptyUsage(), subscription: { ...emptyUsage(), inputTokens: 100, cachedInputTokens: 50, outputTokens: 10 }, unknown: emptyUsage(), unattributedSubscription: emptyUsage(),
|
||||
accounts: [{ id: "account-1", provider: "anthropic", name: "Alice’s Claude", ownerUserId: "alice", ownerName: "Alice", shared: false, identityVerified: true,
|
||||
detectedPlan: "max_5x", observedAt: "2026-10-08T00:00:00Z", lastCheckedAt: "2026-10-08T00:00:00Z", refreshStatus: "ok", canEdit: true,
|
||||
price, usage: emptyUsage(), agents: [{ id: "leela", name: "Leela" }] }],
|
||||
};
|
||||
}
|
||||
|
||||
describe("subscription costs", () => {
|
||||
let container: HTMLDivElement;
|
||||
let root: ReturnType<typeof createRoot>;
|
||||
let client: QueryClient;
|
||||
const changed = vi.fn();
|
||||
beforeEach(() => {
|
||||
container = document.createElement("div"); document.body.appendChild(container); root = createRoot(container);
|
||||
client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });
|
||||
mocks.update.mockResolvedValue({}); mocks.link.mockResolvedValue({}); changed.mockClear();
|
||||
});
|
||||
afterEach(() => { act(() => root.unmount()); container.remove(); client.clear(); vi.clearAllMocks(); });
|
||||
async function render(report?: SubscriptionCostReport, error?: unknown) {
|
||||
await act(async () => root.render(<QueryClientProvider client={client}><SubscriptionCostCard companyId="company" report={report} error={error} onChanged={changed} /></QueryClientProvider>));
|
||||
}
|
||||
async function click(label: string) {
|
||||
await act(async () => [...document.querySelectorAll("button")].find(button => button.textContent === label)!.click());
|
||||
}
|
||||
it("labels the monthly estimate and counts cached input exactly once", async () => {
|
||||
await render(fixture());
|
||||
expect(container.textContent).toContain("$100.00/month");
|
||||
expect(container.textContent).toContain("Estimated");
|
||||
expect(container.textContent).toContain("150 in · 10 out");
|
||||
expect(container.textContent).toContain("50 input cached");
|
||||
await click("View details");
|
||||
expect(document.body.textContent).toContain("Used by Leela");
|
||||
expect(document.body.textContent).toContain("before tax");
|
||||
});
|
||||
it("retains loaded totals during reload failure and never calls an unknown price zero", async () => {
|
||||
const report = fixture();
|
||||
report.monthlyTotals = []; report.unknownPriceCount = 1; report.accounts[0].price.amountCents = null; report.accounts[0].price.monthlyCents = null;
|
||||
await render(report, new Error("private raw error"));
|
||||
expect(container.textContent).toContain("1 price unknown");
|
||||
expect(container.textContent).not.toContain("$0.00");
|
||||
expect(container.textContent).not.toContain("private raw error");
|
||||
await render(fixture(), new Error("private raw error"));
|
||||
expect(container.textContent).toContain("$100.00/month");
|
||||
expect(container.textContent).toContain("last loaded");
|
||||
});
|
||||
it("does not describe legacy subscription usage with no identified account as free", async () => {
|
||||
const report = fixture(); report.accounts = []; report.activeCount = 0; report.monthlyTotals = [];
|
||||
report.unattributedSubscription = { ...report.subscription, eventCount: 1 };
|
||||
await render(report);
|
||||
expect(container.textContent).toContain("No visible subscriptions");
|
||||
expect(container.textContent).not.toContain("$0.00");
|
||||
await click("View details");
|
||||
expect(document.body.textContent).toContain("Some subscription usage has no recorded account");
|
||||
});
|
||||
it("keeps identity uncertainty visible even when a user has supplied the price", async () => {
|
||||
const report = fixture(); report.unidentifiedAccountCount = 1;
|
||||
report.accounts[0].identityVerified = false; report.accounts[0].price.source = "user";
|
||||
report.monthlyTotals[0].estimatedCount = 0;
|
||||
await render(report);
|
||||
expect(container.textContent).toContain("$100.00/month");
|
||||
expect(container.textContent).toContain("1 unconfirmed account identity");
|
||||
});
|
||||
it("saves an annual price with the expected revision and selected currency", async () => {
|
||||
await render(fixture()); await click("View details"); await click("Edit price");
|
||||
await act(async () => {
|
||||
const amount = document.querySelector<HTMLInputElement>("#subscription-price")!;
|
||||
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(amount, "1200");
|
||||
amount.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
const cadence = document.querySelector<HTMLSelectElement>("#subscription-cadence")!;
|
||||
cadence.value = "year"; cadence.dispatchEvent(new Event("change", { bubbles: true }));
|
||||
const currency = document.querySelector<HTMLSelectElement>("#subscription-currency")!;
|
||||
currency.value = "EUR"; currency.dispatchEvent(new Event("change", { bubbles: true }));
|
||||
});
|
||||
await act(async () => document.querySelector("form")!.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true })));
|
||||
await vi.waitFor(() => expect(mocks.update).toHaveBeenCalledWith("company", "account-1", expect.objectContaining({ amountCents: "120000.0000000", currency: "EUR", cadence: "year", expectedRevision: 0 })));
|
||||
expect(changed).toHaveBeenCalled();
|
||||
});
|
||||
it("hides editing when the viewer does not own the account", async () => {
|
||||
const report = fixture(); report.accounts[0].canEdit = false;
|
||||
await render(report); await click("View details");
|
||||
expect([...document.querySelectorAll("button")].some(button => button.textContent === "Edit price")).toBe(false);
|
||||
});
|
||||
it.each(["ended", "excluded"])("can change tracking to %s without rounding a saved fractional price", async (status) => {
|
||||
const report = fixture(); report.accounts[0].price.amountCents = "1575.5000000";
|
||||
await render(report); await click("View details"); await click("Edit price");
|
||||
const amount = document.querySelector<HTMLInputElement>("#subscription-price")!;
|
||||
expect(amount.value).toBe("15.755");
|
||||
expect(amount.checkValidity()).toBe(true);
|
||||
await act(async () => {
|
||||
const tracking = document.querySelector<HTMLSelectElement>("#subscription-status")!;
|
||||
tracking.value = status; tracking.dispatchEvent(new Event("change", { bubbles: true }));
|
||||
});
|
||||
await click("Save price");
|
||||
await vi.waitFor(() => expect(mocks.update).toHaveBeenCalledWith("company", "account-1", expect.objectContaining({
|
||||
amountCents: "1575.5000000", status,
|
||||
})));
|
||||
});
|
||||
it("distinguishes personal seats with multiple owners from company-shared subscriptions", async () => {
|
||||
const report = fixture();
|
||||
report.accounts[0] = { ...report.accounts[0], ownerUserId: null, ownerName: null, shared: false, canEdit: false };
|
||||
await render(report); await click("View details");
|
||||
expect(document.body.textContent).toContain("Personal accounts");
|
||||
expect(document.body.textContent).not.toContain("Shared ·");
|
||||
report.accounts[0].shared = true;
|
||||
await render(report);
|
||||
expect(document.body.textContent).toContain("Shared ·");
|
||||
expect(document.body.textContent).not.toContain("Personal accounts");
|
||||
});
|
||||
it("links only an explicitly chosen duplicate and keeps the target price", async () => {
|
||||
const report = fixture();
|
||||
report.accounts.push({ ...report.accounts[0], id: "account-2", name: "Other connection", price: { ...report.accounts[0].price, revision: 3 } });
|
||||
await render(report); await click("View details"); await click("Edit price");
|
||||
expect(document.body.textContent).toContain("keeps the selected account’s price");
|
||||
await act(async () => { const select = document.querySelector<HTMLSelectElement>("#subscription-link")!; select.value = "account-2"; select.dispatchEvent(new Event("change", { bubbles: true })); });
|
||||
await click("Link accounts");
|
||||
await vi.waitFor(() => expect(mocks.link).toHaveBeenCalledWith("company", "account-1", "account-2", 0, 3));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,117 @@
|
||||
import { useState } from "react";
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import { SUBSCRIPTION_CURRENCIES, centsToUsd, usdToCents, type SubscriptionAccountReport, type SubscriptionCostReport, type SubscriptionUsage } from "@paperclipai/shared";
|
||||
import { subscriptionsApi } from "../api/subscriptions";
|
||||
import { formatCents, formatDateTime, formatTokens, providerDisplayName } from "../lib/utils";
|
||||
import { Button } from "./ui/button";
|
||||
import { Badge } from "./ui/badge";
|
||||
import { Card } from "./ui/card";
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "./ui/dialog";
|
||||
import { Input } from "./ui/input";
|
||||
import { Label } from "./ui/label";
|
||||
|
||||
export function subscriptionMoney(cents: string, currency: string) {
|
||||
return currency === "USD" ? formatCents(Number(cents))
|
||||
: new Intl.NumberFormat(undefined, { style: "currency", currency, currencyDisplay: "code" }).format(Number(cents) / 100);
|
||||
}
|
||||
|
||||
export function SubscriptionTokenUsage({ usage }: { usage: SubscriptionUsage }) {
|
||||
return <span className="font-mono text-xs text-muted-foreground">
|
||||
{formatTokens(usage.inputTokens + usage.cachedInputTokens)} in · {formatTokens(usage.outputTokens)} out
|
||||
{usage.cachedInputTokens > 0 && <span className="block">{formatTokens(usage.cachedInputTokens)} input cached</span>}
|
||||
</span>;
|
||||
}
|
||||
|
||||
function SubscriptionEditor({ account, accounts, companyId, onDone }: {
|
||||
account: SubscriptionAccountReport; accounts: SubscriptionAccountReport[]; companyId: string; onDone: () => void;
|
||||
}) {
|
||||
const [plan, setPlan] = useState(account.price.plan);
|
||||
const [amount, setAmount] = useState(account.price.amountCents == null ? "" : centsToUsd(account.price.amountCents).replace(/\.?0+$/, ""));
|
||||
const [currency, setCurrency] = useState(account.price.currency);
|
||||
const [cadence, setCadence] = useState(account.price.cadence);
|
||||
const [status, setStatus] = useState(account.price.status);
|
||||
const [targetId, setTargetId] = useState("");
|
||||
const save = useMutation({ mutationFn: () => subscriptionsApi.update(companyId, account.id, {
|
||||
expectedRevision: account.price.revision, plan, amountCents: amount.trim() ? usdToCents(amount.trim()) : null,
|
||||
currency: currency as typeof SUBSCRIPTION_CURRENCIES[number], cadence, status,
|
||||
}), onSuccess: onDone });
|
||||
const link = useMutation({ mutationFn: () => subscriptionsApi.link(companyId, account.id, targetId, account.price.revision,
|
||||
accounts.find(row => row.id === targetId)!.price.revision), onSuccess: onDone });
|
||||
const targets = accounts.filter(row => row.id !== account.id && row.provider === account.provider && row.canEdit);
|
||||
const busy = save.isPending || link.isPending;
|
||||
const selectClass = "h-9 rounded-md border border-input bg-background px-3 text-sm";
|
||||
return <div className="space-y-5">
|
||||
<form className="space-y-4" onSubmit={event => { event.preventDefault(); save.mutate(); }}>
|
||||
<div className="space-y-2"><Label htmlFor="subscription-plan">Plan</Label><Input id="subscription-plan" value={plan} onChange={event => setPlan(event.target.value)} required maxLength={100} /></div>
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div className="space-y-2"><Label htmlFor="subscription-price">Price per billing period</Label><Input id="subscription-price" type="number" min="0" step="any" value={amount} placeholder="Unknown" onChange={event => setAmount(event.target.value)} /></div>
|
||||
<div className="space-y-2"><Label htmlFor="subscription-currency">Currency</Label><select id="subscription-currency" className={selectClass} value={currency} onChange={event => setCurrency(event.target.value)}>{SUBSCRIPTION_CURRENCIES.map(code => <option key={code}>{code}</option>)}</select></div>
|
||||
<div className="space-y-2"><Label htmlFor="subscription-cadence">Billed</Label><select id="subscription-cadence" className={selectClass} value={cadence} onChange={event => setCadence(event.target.value as typeof cadence)}><option value="month">Monthly</option><option value="year">Annually</option></select></div>
|
||||
<div className="space-y-2"><Label htmlFor="subscription-status">Tracking</Label><select id="subscription-status" className={selectClass} value={status} onChange={event => setStatus(event.target.value as typeof status)}><option value="active">Active</option><option value="ended">Subscription ended</option><option value="excluded">Exclude from this organization</option></select></div>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">Enter the full amount for one account or seat. Annual prices are divided by 12. Changes apply from now. Ending tracking here does not cancel your provider subscription.</p>
|
||||
{save.error && <p role="alert" className="text-sm text-destructive">Could not save this price. Check the amount, or reopen the account if another person updated it.</p>}
|
||||
<div className="flex items-center justify-between"><Button type="button" variant="ghost" disabled={busy} onClick={onDone}>Cancel</Button><Button type="submit" disabled={busy}>{save.isPending ? "Saving…" : "Save price"}</Button></div>
|
||||
</form>
|
||||
{targets.length > 0 && <div className="space-y-2 border-t border-border pt-4">
|
||||
<Label htmlFor="subscription-link">Same subscription as another account?</Label>
|
||||
<select id="subscription-link" className={selectClass} value={targetId} onChange={event => setTargetId(event.target.value)}><option value="">Choose an account</option>{targets.map(row => <option key={row.id} value={row.id}>{row.name} · {row.price.plan}</option>)}</select>
|
||||
<p className="text-xs text-muted-foreground">Linking counts these accounts once, combines their Paperclip usage, and keeps the selected account’s price. Only link the same subscription or paid seat.</p>
|
||||
{link.error && <p role="alert" className="text-sm text-destructive">Could not link these accounts. Reopen their details and try again.</p>}
|
||||
<Button type="button" variant="outline" disabled={!targetId || busy} onClick={() => link.mutate()}>Link accounts</Button>
|
||||
</div>}
|
||||
</div>;
|
||||
}
|
||||
|
||||
export function SubscriptionCostCard({ companyId, report, error, onChanged }: {
|
||||
companyId: string; report?: SubscriptionCostReport; error?: unknown; onChanged: () => void;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [editing, setEditing] = useState<SubscriptionAccountReport | null>(null);
|
||||
const closeEditor = () => { setEditing(null); onChanged(); };
|
||||
const known = report?.monthlyTotals.length;
|
||||
const estimatedCount = report?.monthlyTotals.reduce((sum, total) => sum + total.estimatedCount, 0) ?? 0;
|
||||
return <>
|
||||
<Card className="block p-4">
|
||||
<div className="text-(length:--text-micro) uppercase tracking-(--tracking-eyebrow) text-muted-foreground">Subscriptions</div>
|
||||
<div className="mt-2 font-mono text-2xl font-semibold tabular-nums">
|
||||
{known ? report!.monthlyTotals.map(total => <div key={total.currency}>{subscriptionMoney(total.amountCents, total.currency)}<span className="text-sm font-normal">/month</span></div>) : report && report.activeCount === 0 && report.accounts.length > 0 ? "$0.00/month" : "—"}
|
||||
</div>
|
||||
<div className="mt-1 space-y-1 text-xs text-muted-foreground">
|
||||
{report ? <>
|
||||
{estimatedCount > 0 && <div><Badge variant="outline" className="font-normal text-muted-foreground">{estimatedCount < report.activeCount - report.unknownPriceCount ? "Partially estimated" : "Estimated"}</Badge></div>}
|
||||
{report.unknownPriceCount > 0 && !!known && <div>Known monthly subtotal</div>}
|
||||
<div>{report.accounts.length === 0 ? "No visible subscriptions" : <>{report.activeCount} active {report.activeCount === 1 ? "subscription" : "subscriptions"}{report.unknownPriceCount > 0 && ` · ${report.unknownPriceCount} ${report.unknownPriceCount === 1 ? "price" : "prices"} unknown`}</>}</div>
|
||||
{report.accounts.length > 0 && <div>Monthly fees for accounts visible to you</div>}
|
||||
{report.unidentifiedAccountCount > 0 && <div>{report.unidentifiedAccountCount} unconfirmed {report.unidentifiedAccountCount === 1 ? "account identity" : "account identities"}</div>}
|
||||
<SubscriptionTokenUsage usage={report.subscription} />
|
||||
</> : error ? <div>Subscription data is unavailable.</div> : <div>Loading subscriptions…</div>}
|
||||
{report && error ? <div>Showing last loaded subscription data.</div> : null}
|
||||
</div>
|
||||
<Button variant="link" size="sm" className="h-auto p-0" onClick={() => setOpen(true)} disabled={!report}>View details</Button>
|
||||
</Card>
|
||||
<Dialog open={open} onOpenChange={value => { setOpen(value); if (!value) setEditing(null); }}>
|
||||
<DialogContent className="max-h-(--sz-80vh) overflow-y-auto sm:max-w-3xl">
|
||||
<DialogHeader><DialogTitle>{editing ? "Subscription price" : "Subscriptions"}</DialogTitle><DialogDescription>Current monthly costs for accounts visible to you. Token totals cover company work in the selected period.</DialogDescription></DialogHeader>
|
||||
{editing ? <SubscriptionEditor key={editing.id} companyId={companyId} account={editing} accounts={report?.accounts ?? []} onDone={closeEditor} /> : <div className="space-y-4">
|
||||
{report?.accounts.length === 0 && <p className="text-sm text-muted-foreground">No subscriptions are visible to you yet. Connect an AI account or run an agent with a connected subscription.</p>}
|
||||
{report?.accounts.map(account => <div key={account.id} className="space-y-2 border-b border-border pb-4 last:border-0">
|
||||
<div className="flex flex-wrap items-start justify-between gap-3">
|
||||
<div><div className="font-medium">{account.name}</div><div className="text-xs text-muted-foreground">{account.shared ? "Shared" : account.ownerName ?? (account.ownerUserId ? "Account owner" : "Personal accounts")} · {providerDisplayName(account.provider)} · {account.price.plan}</div></div>
|
||||
<div className="text-right"><div className="font-mono">{account.price.status !== "active" ? account.price.status === "ended" ? "Ended" : "Excluded" : account.price.monthlyCents == null ? "Price unknown" : `${subscriptionMoney(account.price.monthlyCents, account.price.currency)}/month`}</div><div className="text-xs text-muted-foreground">{account.price.source === "catalog" ? "Estimated · before tax" : account.price.source === "user" ? "User supplied" : ""}{account.price.cadence === "year" ? " · annual payment ÷ 12" : ""}</div></div>
|
||||
</div>
|
||||
<SubscriptionTokenUsage usage={account.usage} />
|
||||
{Number(account.usage.costCents) > 0 && <div className="text-xs text-muted-foreground">{formatCents(Number(account.usage.costCents))} recorded usage charges in selected period, separate from the subscription fee.</div>}
|
||||
{account.agents.length > 0 && <div className="text-xs text-muted-foreground">Used by {account.agents.map(agent => agent.name).join(", ")}</div>}
|
||||
{!account.identityVerified && <p className="text-xs text-muted-foreground">Account identity is unconfirmed. Link duplicates if these connections use the same subscription.</p>}
|
||||
{account.observedAt && <div className="text-xs text-muted-foreground">Plan checked {formatDateTime(account.observedAt)}{account.refreshStatus === "unavailable" ? " · latest check unavailable" : ""}</div>}
|
||||
{account.refreshStatus === "unavailable" && !account.observedAt && <p className="text-xs text-muted-foreground">The provider did not make plan details available. You can enter the price yourself.</p>}
|
||||
{account.canEdit && <div><Button variant="outline" size="sm" onClick={() => setEditing(account)}>Edit price</Button></div>}
|
||||
</div>)}
|
||||
{!!report?.unattributedSubscription.eventCount && <p className="text-xs text-muted-foreground">Some subscription usage has no recorded account. It is included in the subscription token total.</p>}
|
||||
<p className="text-xs text-muted-foreground">Monthly fees cover the whole account, including use outside Paperclip. They are separate from recorded charges and agent budgets. Currencies are totaled separately.</p>
|
||||
</div>}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>;
|
||||
}
|
||||
@@ -8,8 +8,8 @@ import { cn } from "@/lib/utils";
|
||||
|
||||
export type ExternalAgentPreset = "dot" | "hermes" | "other";
|
||||
export type DotConnectionState = {
|
||||
phase: "waiting" | "connected" | "subscribed" | "testing" | "ready";
|
||||
problem?: "event_timeout" | "prompt_unavailable" | "offline";
|
||||
phase: "waiting" | "connected" | "subscribed" | "testing" | "finishing" | "ready";
|
||||
problem?: "event_timeout" | "prompt_unavailable" | "offline" | "agent_unavailable";
|
||||
};
|
||||
|
||||
const presets = [
|
||||
@@ -43,10 +43,12 @@ const checks = [
|
||||
|
||||
/** Controlled by server evidence in the invite controller, never by copying a prompt. */
|
||||
export function DotConnectionChecks({ state }: { state: DotConnectionState }) {
|
||||
const completed = { waiting: 0, connected: 1, subscribed: 2, testing: 2, ready: 3 }[state.phase];
|
||||
const message = state.problem === "offline" ? "Connection updates paused. Reconnect to check the latest status."
|
||||
const completed = { waiting: 0, connected: 1, subscribed: 2, testing: 2, finishing: 3, ready: 3 }[state.phase];
|
||||
const message = state.problem === "agent_unavailable" ? "Connection checks passed, but this agent cannot receive tasks. Resolve the agent’s setup blocker in Paperclip."
|
||||
: state.problem === "offline" ? "Connection updates paused. Reconnect to check the latest status."
|
||||
: state.problem === "prompt_unavailable" ? "This setup prompt was replaced in another window. Create a fresh prompt to continue."
|
||||
: state.problem === "event_timeout" ? "Your Dot connected, but hasn’t confirmed the test event. Ask it to check Paperclip, then retry."
|
||||
: state.phase === "finishing" ? "Your Dot confirmed the test event. Paperclip is finishing agent setup."
|
||||
: state.phase === "ready" ? "Your Dot is ready for tasks. Messages can travel both ways."
|
||||
: state.phase === "waiting" ? "Watching for your Dot. Updates will appear here automatically."
|
||||
: state.phase === "connected" ? "Your Dot connected. Waiting for it to enable task updates."
|
||||
@@ -99,8 +101,10 @@ export function ExternalAgentInviteContent({
|
||||
const dot = preset === "dot";
|
||||
const ready = dot && connection.phase === "ready" && !connection.problem;
|
||||
const connecting = dot && connection.phase !== "waiting";
|
||||
const progressLabel = connection.problem === "offline" ? "Updates paused"
|
||||
const progressLabel = connection.problem === "agent_unavailable" ? "Agent unavailable"
|
||||
: connection.problem === "offline" ? "Updates paused"
|
||||
: connection.problem === "event_timeout" ? "Needs attention"
|
||||
: connection.phase === "finishing" ? "Finishing setup…"
|
||||
: connection.phase === "connected" ? "Connecting…" : "Confirming connection…";
|
||||
return <>
|
||||
<div className="min-h-0 space-y-6 overflow-y-auto px-6 pb-6 pt-8 sm:px-8">
|
||||
@@ -113,6 +117,8 @@ export function ExternalAgentInviteContent({
|
||||
<DialogDescription className="text-sm leading-relaxed">
|
||||
{!provider ? `Bring an agent you already use into ${companyName}.`
|
||||
: ready ? `Your Dot can now receive assignments and work with ${companyName}.`
|
||||
: connection.problem === "agent_unavailable" ? "Your Dot is connected. This agent must be available in Paperclip before it can receive assignments."
|
||||
: connection.phase === "finishing" ? "Your Dot has connected and confirmed task updates. Paperclip is preparing it for assignments."
|
||||
: connecting ? "Your Dot has connected. We’re checking that task updates can travel both ways."
|
||||
: dot ? "Copy the setup prompt and send it to your Dot in ChatGPT. Your Dot will connect itself; we’ll watch for it here."
|
||||
: `Copy the invitation prompt and send it to your ${preset === "hermes" ? "Hermes " : ""}agent. Approve its join request in Paperclip when it’s ready.`}
|
||||
|
||||
@@ -36,7 +36,8 @@ export function ExternalAgentInviteDialog({ companyId, onClose, onBack }: {
|
||||
enabled: preset === "dot" && !!invitation,
|
||||
retry: false,
|
||||
staleTime: 0,
|
||||
refetchInterval: query => query.state.error ? false : query.state.data?.binding?.status === "ready" && query.state.data.binding.subscriptionVerified ? false : 2500,
|
||||
refetchInterval: query => query.state.error ? false : query.state.data?.agentLifecycleState === "ready" && query.state.data.canConfigureConnection
|
||||
&& query.state.data.binding?.status === "ready" && query.state.data.binding.subscriptionVerified ? false : 2500,
|
||||
});
|
||||
const generate = useMutation({
|
||||
mutationFn: async (kind: ExternalAgentPreset) => {
|
||||
@@ -71,7 +72,7 @@ export function ExternalAgentInviteDialog({ companyId, onClose, onBack }: {
|
||||
onSuccess: () => { void cache.invalidateQueries({ queryKey: key }); } });
|
||||
const binding = state.data?.binding;
|
||||
const canPreparePairing = preset === "dot" && state.data?.enabled && !!state.data.resourceUrl
|
||||
&& !["pending_approval", "paused", "terminated"].includes(state.data.agentStatus)
|
||||
&& state.data.canConfigureConnection
|
||||
&& (!binding || binding.status === "pairing");
|
||||
const preparePairing = canPreparePairing && !pairing && !state.error && !pair.isError
|
||||
&& !attemptedAutomaticPairing.current
|
||||
@@ -93,15 +94,20 @@ export function ExternalAgentInviteDialog({ companyId, onClose, onBack }: {
|
||||
}, Math.max(0, Date.parse(pairing.expiresAt) - Date.now()));
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [pairing]);
|
||||
const checksReady = binding?.status === "ready" && binding.subscriptionVerified;
|
||||
const agentReady = state.data?.agentLifecycleState === "ready" && state.data.canConfigureConnection;
|
||||
const finishingSetup = ["preparing", "verifying"].includes(state.data?.agentLifecycleState ?? "")
|
||||
&& state.data?.canConfigureConnection;
|
||||
const connection: DotConnectionState = {
|
||||
phase: binding?.status === "ready" && binding.subscriptionVerified && !["paused", "terminated", "pending_approval"].includes(state.data?.agentStatus ?? "") ? "ready"
|
||||
phase: checksReady ? agentReady ? "ready" : finishingSetup ? "finishing" : "ready"
|
||||
: binding?.hasPendingChallenge ? "testing" : binding?.subscriptionVerified ? "subscribed" : binding?.connected ? "connected" : "waiting",
|
||||
problem: state.error ? "offline"
|
||||
: checksReady && !agentReady && !finishingSetup ? "agent_unavailable"
|
||||
: binding?.status === "pairing" && !preparePairing && !pair.isPending && !state.isFetching && !pair.isError && pairing?.bindingId !== binding.id ? "prompt_unavailable"
|
||||
: binding?.challengeExpiresAt && !binding.hasPendingChallenge && binding.status !== "ready" ? "event_timeout" : undefined,
|
||||
};
|
||||
const pendingApproval = (state.data?.agentStatus ?? invitation?.agent.status) === "pending_approval";
|
||||
const unavailable = state.data && ["paused", "terminated"].includes(state.data.agentStatus);
|
||||
const unavailable = state.data && !state.data.canConfigureConnection && !pendingApproval;
|
||||
const prompt = preset === "dot" ? pairing && pairing.bindingId === binding?.id && state.data?.resourceUrl && invitation
|
||||
? buildDotSetupPrompt({ companyId, agentId: invitation.agent.id, resourceUrl: state.data.resourceUrl, ...pairing }) : "" : genericPrompt;
|
||||
const error = (generate.variables === preset ? generate.error : null) ?? (preset === "dot" ? (binding?.connected ? null : pair.error) ?? test.error : null);
|
||||
@@ -118,7 +124,7 @@ export function ExternalAgentInviteDialog({ companyId, onClose, onBack }: {
|
||||
<AnimatedDialogContent className="sm:max-w-(--sz-560px)">
|
||||
<ExternalAgentInviteContent preset={preset} prompt={prompt} companyName={selectedCompany?.name ?? "your organization"}
|
||||
connection={connection} dotDisabledReason={dotDisabledReason} busy={busy}
|
||||
error={error?.message ?? (unavailable ? "Resume this agent before connecting Dot." : undefined)}
|
||||
error={error?.message ?? (unavailable ? state.data?.agentLifecycleState === "terminated" ? "This agent was terminated. Invite another agent to connect Dot." : "Resume this agent before connecting Dot." : undefined)}
|
||||
approvalHref={pendingApproval && invitation?.approvalId ? `/approvals/${invitation.approvalId}` : undefined}
|
||||
onSelect={kind => { setPreset(kind); if (kind === "dot" ? !invitation : !genericPrompt) generate.mutate(kind); }}
|
||||
onBack={() => setPreset(null)} onClose={preset ? onClose : onBack} onCopied={() => { if (preset === "dot") void state.refetch(); }}
|
||||
|
||||
@@ -7,6 +7,11 @@ import {
|
||||
} from "./company-routes";
|
||||
|
||||
describe("company routes", () => {
|
||||
it("keeps public Dot consent outside company-prefixed routes", () => {
|
||||
const path = `/dot-connect/pcmcp_request_${"a".repeat(43)}`;
|
||||
expect(extractCompanyPrefixFromPath(path)).toBeNull();
|
||||
expect(applyCompanyPrefix(path, "DOT")).toBe(path);
|
||||
});
|
||||
it("treats the task-list alias as an unprefixed board route", () => {
|
||||
expect(isBoardPathWithoutPrefix("/tasks")).toBe(true);
|
||||
expect(extractCompanyPrefixFromPath("/tasks")).toBeNull();
|
||||
|
||||
@@ -33,7 +33,7 @@ const BOARD_ROUTE_ROOTS = new Set([
|
||||
"timeline",
|
||||
]);
|
||||
|
||||
const GLOBAL_ROUTE_ROOTS = new Set(["auth", "invite", "board-claim", "cli-auth", "mcp-connect", "assistant-connections", "docs", "instance"]);
|
||||
const GLOBAL_ROUTE_ROOTS = new Set(["auth", "invite", "board-claim", "cli-auth", "mcp-connect", "dot-connect", "assistant-connections", "docs", "instance"]);
|
||||
|
||||
export function normalizeCompanyPrefix(prefix: string): string {
|
||||
return prefix.trim().toUpperCase();
|
||||
|
||||
@@ -43,6 +43,36 @@ describe("isArchivedStackRecoveryError", () => {
|
||||
});
|
||||
|
||||
describe("tenant-session recovery coordinator", () => {
|
||||
it.each(["tenant_session_required", "tenant_session_invalid"])(
|
||||
"leaves public Dot consent mounted after an expected %s background failure",
|
||||
(error) => {
|
||||
const reload = vi.fn();
|
||||
const pathname = `/dot-connect/pcmcp_request_${"a".repeat(43)}`;
|
||||
const recovery = createTenantSessionRecoveryCoordinator(reload, () => pathname);
|
||||
|
||||
expect(recovery.recoverIfNeeded(401, { error })).toBeNull();
|
||||
expect(reload).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["/DOT/agents/dot", "/dot-connect/not-a-request", `/dot-connect/pcmcp_request_${"a".repeat(43)}/extra`])(
|
||||
"still recovers tenant sessions outside the public consent route: %s",
|
||||
(pathname) => {
|
||||
const reload = vi.fn();
|
||||
const recovery = createTenantSessionRecoveryCoordinator(reload, () => pathname);
|
||||
|
||||
expect(recovery.recoverIfNeeded(401, { error: "tenant_session_required" })).not.toBeNull();
|
||||
expect(reload).toHaveBeenCalledTimes(1);
|
||||
},
|
||||
);
|
||||
|
||||
it("still leaves archived stacks from the public Dot consent route", () => {
|
||||
const reload = vi.fn();
|
||||
const recovery = createTenantSessionRecoveryCoordinator(reload, () => `/dot-connect/pcmcp_request_${"a".repeat(43)}`);
|
||||
|
||||
expect(recovery.recoverIfNeeded(423, { statusPage: { code: "archived" } })).not.toBeNull();
|
||||
expect(reload).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
it("reloads once and shares one never-settling promise across concurrent failures", async () => {
|
||||
const reload = vi.fn();
|
||||
const recovery = createTenantSessionRecoveryCoordinator(reload);
|
||||
|
||||
@@ -40,12 +40,22 @@ export interface TenantSessionRecoveryCoordinator {
|
||||
|
||||
export function createTenantSessionRecoveryCoordinator(
|
||||
reloadTopLevelPage: () => void,
|
||||
getDocumentPathname: () => string = () => "",
|
||||
): TenantSessionRecoveryCoordinator {
|
||||
let recoveryPromise: Promise<never> | null = null;
|
||||
|
||||
return {
|
||||
recoverIfNeeded(status, body) {
|
||||
if (!isTenantDocumentRecoveryError(status, body)) return null;
|
||||
// Dot consent is intentionally public. Global settings/session probes can
|
||||
// receive an expected 401 here; reloading would repeat that probe forever
|
||||
// and prevent the public connection request from finishing. Leave those
|
||||
// failures to their consumers while preserving recovery on board routes
|
||||
// and for archived stacks.
|
||||
if (
|
||||
isTenantSessionRecoveryError(status, body)
|
||||
&& /^\/dot-connect\/pcmcp_request_[A-Za-z0-9_-]{43}$/.test(getDocumentPathname())
|
||||
) return null;
|
||||
if (recoveryPromise) return recoveryPromise;
|
||||
|
||||
// Keep every affected consumer pending while the browser leaves this
|
||||
@@ -70,4 +80,4 @@ export const tenantSessionRecovery = createTenantSessionRecoveryCoordinator(() =
|
||||
// stack is redirected to the portfolio.
|
||||
const topLevelWindow = window.top ?? window;
|
||||
topLevelWindow.location.reload();
|
||||
});
|
||||
}, () => typeof window === "undefined" ? "" : window.location.pathname);
|
||||
@@ -28,6 +28,8 @@ const costsApiMocks = vi.hoisted(() => ({
|
||||
windowSpend: vi.fn(),
|
||||
quotaWindows: vi.fn(),
|
||||
}));
|
||||
const subscriptionsMocks = vi.hoisted(() => ({ report: vi.fn(), refresh: vi.fn(), update: vi.fn(), link: vi.fn() }));
|
||||
vi.mock("../api/subscriptions", () => ({ subscriptionsApi: subscriptionsMocks }));
|
||||
|
||||
vi.mock("../api/budgets", () => ({
|
||||
budgetsApi: {
|
||||
@@ -63,6 +65,8 @@ describe("Shared Costs surfaces", () => {
|
||||
let root: ReturnType<typeof createRoot>;
|
||||
|
||||
beforeEach(() => {
|
||||
const usage = { inputTokens: 0, cachedInputTokens: 0, outputTokens: 0, costCents: "0", eventCount: 0, estimatedEventCount: 0, unpricedEventCount: 0 };
|
||||
subscriptionsMocks.report.mockResolvedValue({ canRefresh: false, asOf: "2026-10-08T00:00:00Z", accounts: [], monthlyTotals: [], activeCount: 0, unknownPriceCount: 0, unidentifiedAccountCount: 0, api: usage, subscription: usage, unknown: usage, unattributedSubscription: usage });
|
||||
decisionHistoryMock.mockResolvedValue([]);
|
||||
costsApiMocks.byUser.mockResolvedValue({ activeUserCount: 1, rows: [] });
|
||||
container = document.createElement("div");
|
||||
@@ -92,6 +96,24 @@ describe("Shared Costs surfaces", () => {
|
||||
expect(container.textContent).toContain("1 unpriced charge");
|
||||
});
|
||||
|
||||
it.each(surfaces)("labels other and unknown billing accurately on the %s surface", async (_name, props) => {
|
||||
for (const mock of Object.values(costsApiMocks)) mock.mockResolvedValue([]);
|
||||
costsApiMocks.byUser.mockResolvedValue({ activeUserCount: 1, rows: [] });
|
||||
costsApiMocks.summary.mockResolvedValue({ spendCents: 600, budgetCents: 0, pricingComplete: true });
|
||||
costsApiMocks.financeSummary.mockResolvedValue({ netCents: 0, debitCents: 0, creditCents: 0, estimatedDebitCents: 0, eventCount: 0 });
|
||||
const report = await subscriptionsMocks.report();
|
||||
subscriptionsMocks.report.mockResolvedValue({ ...report, unknown: { ...report.unknown,
|
||||
inputTokens: 100, cachedInputTokens: 40, outputTokens: 10, costCents: "600", eventCount: 3,
|
||||
} });
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
root = createRoot(container);
|
||||
await act(async () => root.render(<MemoryRouter><QueryClientProvider client={queryClient}><Costs {...props} /></QueryClientProvider></MemoryRouter>));
|
||||
await act(async () => vi.waitFor(() => expect(container.textContent).toContain(
|
||||
"150 tokens have other or unknown billing types, with $6.00 in recorded charges. They remain in the inference ledger.",
|
||||
)));
|
||||
expect(container.textContent).not.toContain("tokens have an unknown billing type");
|
||||
});
|
||||
|
||||
it("renders a focused Budgets section without duplicate Costs chrome or spend queries", async () => {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
root = createRoot(container);
|
||||
@@ -212,6 +234,56 @@ describe("Shared Costs surfaces", () => {
|
||||
queryClient.clear();
|
||||
});
|
||||
|
||||
it("retries failed account discovery without discarding the last subscription report", async () => {
|
||||
for (const mock of Object.values(costsApiMocks)) mock.mockResolvedValue([]);
|
||||
costsApiMocks.byUser.mockResolvedValue({ activeUserCount: 1, rows: [] });
|
||||
costsApiMocks.summary.mockResolvedValue({ spendCents: 0, budgetCents: 0, pricingComplete: true });
|
||||
costsApiMocks.financeSummary.mockResolvedValue({ netCents: 0, debitCents: 0, creditCents: 0, estimatedDebitCents: 0, eventCount: 0 });
|
||||
const report = await subscriptionsMocks.report();
|
||||
subscriptionsMocks.report.mockResolvedValue({ ...report, canRefresh: true, activeCount: 1, monthlyTotals: [{ currency: "USD", amountCents: "2000", estimatedCount: 1 }] });
|
||||
subscriptionsMocks.refresh.mockRejectedValueOnce(new Error("private connection error")).mockResolvedValue({});
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
root = createRoot(container);
|
||||
await act(async () => root.render(<MemoryRouter><QueryClientProvider client={queryClient}><Costs /></QueryClientProvider></MemoryRouter>));
|
||||
const retry = () => [...container.querySelectorAll("button")].find(button => button.textContent === "Retry account check");
|
||||
await act(async () => { await vi.waitFor(() => expect(retry()).toBeDefined()); });
|
||||
expect(container.textContent).toContain("$20.00/month");
|
||||
expect(container.textContent).not.toContain("private connection error");
|
||||
await act(async () => retry()!.click());
|
||||
await act(async () => { await vi.waitFor(() => expect(retry()).toBeUndefined()); });
|
||||
expect(subscriptionsMocks.refresh).toHaveBeenCalledTimes(2);
|
||||
expect(subscriptionsMocks.refresh).toHaveBeenLastCalledWith("company-1");
|
||||
expect(container.textContent).toContain("$20.00/month");
|
||||
queryClient.clear();
|
||||
});
|
||||
|
||||
it("keeps monthly subscription fees through date changes and failed background reloads", async () => {
|
||||
for (const mock of Object.values(costsApiMocks)) mock.mockResolvedValue([]);
|
||||
costsApiMocks.byUser.mockResolvedValue({ activeUserCount: 1, rows: [] });
|
||||
costsApiMocks.summary.mockResolvedValue({ spendCents: 200, budgetCents: 0, pricingComplete: true });
|
||||
costsApiMocks.financeSummary.mockResolvedValue({ netCents: 0, debitCents: 0, creditCents: 0, estimatedDebitCents: 0, eventCount: 0 });
|
||||
const report = await subscriptionsMocks.report();
|
||||
subscriptionsMocks.report.mockResolvedValue({ ...report, activeCount: 1, monthlyTotals: [{ currency: "USD", amountCents: "2000", estimatedCount: 1 }], api: { ...report.api, costCents: "200" } });
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
root = createRoot(container);
|
||||
await act(async () => root.render(<MemoryRouter><QueryClientProvider client={queryClient}><Costs /></QueryClientProvider></MemoryRouter>));
|
||||
const card = (label: string) => [...container.querySelectorAll("div")].find(node => node.textContent === label)?.closest('[data-slot="card"]');
|
||||
await act(async () => { await vi.waitFor(() => expect(card("Subscriptions")?.textContent).toContain("$20.00/month")); });
|
||||
expect(card("API spend")?.textContent).toContain("$2.00");
|
||||
subscriptionsMocks.report.mockResolvedValue({ ...report, activeCount: 1, monthlyTotals: [{ currency: "USD", amountCents: "2000", estimatedCount: 1 }], api: { ...report.api, costCents: "300" } });
|
||||
await act(async () => [...container.querySelectorAll("button")].find(button => button.textContent === "All Time")!.click());
|
||||
await act(async () => { await vi.waitFor(() => expect(card("API spend")?.textContent).toContain("$3.00")); });
|
||||
expect(card("Subscriptions")?.textContent).toContain("$20.00/month");
|
||||
expect(subscriptionsMocks.report).toHaveBeenLastCalledWith("company-1", undefined, undefined);
|
||||
subscriptionsMocks.report.mockRejectedValue(new Error("private provider failure"));
|
||||
await act(async () => { await queryClient.invalidateQueries({ queryKey: ["cost-subscriptions"] }); });
|
||||
await act(async () => { await vi.waitFor(() => expect(container.textContent).toContain("Showing the last loaded API and subscription usage")); });
|
||||
expect(card("API spend")?.textContent).toContain("$3.00");
|
||||
expect(card("Subscriptions")?.textContent).toContain("$20.00/month");
|
||||
expect(container.textContent).not.toContain("private provider failure");
|
||||
queryClient.clear();
|
||||
});
|
||||
|
||||
it("compares monthly budgets only with month-to-date spend", async () => {
|
||||
for (const mock of Object.values(costsApiMocks)) mock.mockResolvedValue([]);
|
||||
costsApiMocks.byUser.mockResolvedValue({ activeUserCount: 1, rows: [] });
|
||||
@@ -224,6 +296,8 @@ describe("Shared Costs surfaces", () => {
|
||||
await act(async () => { await vi.waitFor(() => expect(budgetCard()?.textContent).toContain("20%")); });
|
||||
expect(budgetCard()?.textContent).toContain("$2.00 of $10.00 this month");
|
||||
costsApiMocks.summary.mockResolvedValue({ spendCents: 12000, budgetCents: 1000, utilizationPercent: 1200, pricingComplete: true });
|
||||
const subscriptionReport = await subscriptionsMocks.report();
|
||||
subscriptionsMocks.report.mockResolvedValue({ ...subscriptionReport, api: { ...subscriptionReport.api, costCents: "12000" } });
|
||||
await act(async () => [...container.querySelectorAll("button")].find(b => b.textContent === "All Time")!.click());
|
||||
await act(async () => { await vi.waitFor(() => expect(container.textContent).toContain("$120.00")); });
|
||||
expect(budgetCard()?.textContent).toContain("$10.00");
|
||||
@@ -281,7 +355,7 @@ describe("Shared Costs surfaces", () => {
|
||||
expect(notice.querySelector(".text-destructive")).toBeNull();
|
||||
expect(notice.classList.contains("text-destructive")).toBe(false);
|
||||
expect(notice.textContent).toContain("1 run is awaiting cost data.");
|
||||
expect(notice.previousElementSibling?.textContent).toContain("Inference spend");
|
||||
expect(notice.previousElementSibling?.textContent).toContain("API spend");
|
||||
expect(container.textContent).toContain("Finance headline totals are USD only");
|
||||
costsApiMocks.summary.mockResolvedValue({ spendCents: 12.4, budgetCents: 0, pricingComplete: false, unpricedEventCount: 10, pendingRunCount: 0 });
|
||||
await act(async () => { await queryClient.invalidateQueries(); });
|
||||
@@ -296,12 +370,17 @@ describe("Shared Costs surfaces", () => {
|
||||
await vi.waitFor(() => expect(container.contains(notice)).toBe(false));
|
||||
});
|
||||
|
||||
it.each(surfaces)("labels each agent and expanded model independently on the %s page", async (_name, props) => {
|
||||
it.each(surfaces)("labels each agent, project, and expanded model independently on the %s page", async (_name, props) => {
|
||||
for (const mock of Object.values(costsApiMocks)) mock.mockResolvedValue([]);
|
||||
costsApiMocks.byUser.mockResolvedValue({ activeUserCount: 1, rows: [] });
|
||||
costsApiMocks.summary.mockResolvedValue({ spendCents: 600, budgetCents: 0, pricingComplete: true, estimatedEventCount: 3 });
|
||||
costsApiMocks.financeSummary.mockResolvedValue({ netCents: 0, debitCents: 0, creditCents: 0, estimatedDebitCents: 0, eventCount: 0 });
|
||||
const base = { costCents: 200, inputTokens: 10, cachedInputTokens: 5, outputTokens: 2, apiRunCount: 2, subscriptionRunCount: 0, eventCount: 2 };
|
||||
costsApiMocks.byProject.mockResolvedValue([
|
||||
{ ...base, projectId: "estimated-project", projectName: "Estimated project", estimatedEventCount: 2 },
|
||||
{ ...base, projectId: "mixed-project", projectName: "Mixed project", estimatedEventCount: 1 },
|
||||
{ ...base, projectId: "reported-project", projectName: "Reported project", estimatedEventCount: 0 },
|
||||
]);
|
||||
costsApiMocks.byAgent.mockResolvedValue([
|
||||
{ ...base, agentId: "codie", agentName: "Codie", estimatedEventCount: 2 },
|
||||
{ ...base, agentId: "mixed", agentName: "Mixed", estimatedEventCount: 1 },
|
||||
@@ -326,6 +405,11 @@ describe("Shared Costs surfaces", () => {
|
||||
expect(card("Mixed").textContent).toContain("Partially estimated");
|
||||
expect(card("Reported").textContent).not.toMatch(/Estimated|Partially estimated/);
|
||||
expect(card("Legacy").textContent).not.toMatch(/Estimated|Partially estimated/);
|
||||
const projectBadge = (name: string) => [...container.querySelectorAll("span")]
|
||||
.find(element => element.textContent === name)!.parentElement!.querySelector('[data-slot="badge"]');
|
||||
expect(projectBadge("Estimated project")?.textContent).toBe("Estimated");
|
||||
expect(projectBadge("Mixed project")?.textContent).toBe("Partially estimated");
|
||||
expect(projectBadge("Reported project")).toBeNull();
|
||||
await act(async () => card("Mixed").querySelector<HTMLElement>(".cursor-pointer")!.click());
|
||||
const breakdown = card("Mixed").querySelector(".border-l")!;
|
||||
expect(breakdown.textContent).toContain("gpt-6-astra");
|
||||
|
||||
+54
-30
@@ -1,6 +1,9 @@
|
||||
import { DecisionHistory } from "../components/decision-models/DecisionHistory";
|
||||
import { SubscriptionCostCard, SubscriptionTokenUsage } from "../components/SubscriptionCostCard";
|
||||
import { subscriptionsApi } from "../api/subscriptions";
|
||||
import { useSearchParams } from "@/lib/router";
|
||||
import { CostEstimateLabel } from "../components/CostEstimateLabel";
|
||||
import { CostAmount } from "../components/CostAmount";
|
||||
import { CostByUserTable } from "../components/CostByUserTable";
|
||||
import { AgentIdentity } from "@/components/AgentIdentity";
|
||||
import { useEffect, useMemo, useRef, useState, type ComponentType, type ReactNode } from "react";
|
||||
@@ -228,6 +231,23 @@ export function Costs({
|
||||
const reportQueryFrom = ["custom", "mtd", "ytd"].includes(preset) ? from || undefined : undefined;
|
||||
const reportQueryTo = preset === "custom" ? to || undefined : preset;
|
||||
|
||||
const subscriptionKey = ["cost-subscriptions", companyId, reportQueryFrom, reportQueryTo];
|
||||
const { data: subscriptions, error: subscriptionError } = useQuery({
|
||||
queryKey: subscriptionKey,
|
||||
queryFn: () => subscriptionsApi.report(companyId, from || undefined, to || undefined),
|
||||
enabled: !!selectedCompanyId && customReady && showSummaryChrome,
|
||||
refetchInterval: 30_000,
|
||||
});
|
||||
const invalidateSubscriptions = () => { void queryClient.invalidateQueries({ queryKey: ["cost-subscriptions", companyId] }); };
|
||||
const discoveryCompany = useRef<string | null>(null);
|
||||
const discoverSubscriptions = useMutation({ mutationFn: (id: string) => subscriptionsApi.refresh(id),
|
||||
onSuccess: (_data, id) => { void queryClient.invalidateQueries({ queryKey: ["cost-subscriptions", id] }); } });
|
||||
useEffect(() => {
|
||||
if (!selectedCompanyId || !showSummaryChrome || !subscriptions?.canRefresh || discoveryCompany.current === selectedCompanyId) return;
|
||||
discoveryCompany.current = selectedCompanyId;
|
||||
discoverSubscriptions.mutate(selectedCompanyId);
|
||||
}, [selectedCompanyId, showSummaryChrome, subscriptions?.canRefresh, discoverSubscriptions.mutate]);
|
||||
|
||||
const { data: budgetData, isLoading: budgetLoading, error: budgetError } = useQuery({
|
||||
queryKey: queryKeys.budgets.overview(companyId),
|
||||
queryFn: () => budgetsApi.overview(companyId),
|
||||
@@ -558,12 +578,6 @@ export function Costs({
|
||||
];
|
||||
}, [byBiller]);
|
||||
|
||||
const inferenceTokenTotal =
|
||||
(spendData?.byAgent ?? []).reduce(
|
||||
(sum, row) => sum + row.inputTokens + row.cachedInputTokens + row.outputTokens,
|
||||
0,
|
||||
);
|
||||
|
||||
const topFinanceEvents = (financeData?.events ?? []) as FinanceEvent[];
|
||||
const budgetPolicies = budgetData?.policies ?? [];
|
||||
const activeBudgetIncidents = budgetData?.activeIncidents ?? [];
|
||||
@@ -631,13 +645,17 @@ export function Costs({
|
||||
Finance headline totals are USD only. Other currencies are listed separately; no exchange-rate conversion is applied.
|
||||
</p>
|
||||
)}
|
||||
<div className="grid gap-3 lg:grid-cols-4">
|
||||
<div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-5">
|
||||
<MetricTile
|
||||
label="Inference spend"
|
||||
value={spendData ? formatCents(spendData.summary.spendCents) : "—"}
|
||||
subtitle={`${formatTokens(inferenceTokenTotal)} tokens across request-scoped events`}
|
||||
label="API spend"
|
||||
value={subscriptions ? subscriptions.api.unpricedEventCount === subscriptions.api.eventCount && subscriptions.api.eventCount > 0 ? "—" : formatCents(Number(subscriptions.api.costCents)) : "—"}
|
||||
subtitle={subscriptions ? <div className="space-y-1">
|
||||
<CostEstimateLabel eventCount={subscriptions.api.eventCount} estimatedEventCount={subscriptions.api.estimatedEventCount} />
|
||||
<div><SubscriptionTokenUsage usage={subscriptions.api} /></div>
|
||||
</div> : subscriptionError ? "API usage is unavailable" : "API usage is loading"}
|
||||
icon={DollarSign}
|
||||
/>
|
||||
<SubscriptionCostCard key={companyId} companyId={companyId} report={subscriptions} error={subscriptionError} onChanged={invalidateSubscriptions} />
|
||||
<MetricTile
|
||||
label="Budget"
|
||||
value={activeBudgetIncidents.length > 0 ? String(activeBudgetIncidents.length) : (
|
||||
@@ -672,6 +690,14 @@ export function Costs({
|
||||
icon={ArrowUpRight}
|
||||
/>
|
||||
</div>
|
||||
{subscriptions && Number(subscriptions.subscription.costCents) > 0 && <p className="text-sm text-muted-foreground">Subscription accounts also have {formatCents(Number(subscriptions.subscription.costCents))} in recorded usage charges for this period, separate from monthly fees.</p>}
|
||||
{subscriptions && subscriptions.unknown.eventCount > 0 && <p className="text-sm text-muted-foreground">{formatTokens(subscriptions.unknown.inputTokens + subscriptions.unknown.cachedInputTokens + subscriptions.unknown.outputTokens)} tokens have other or unknown billing types{Number(subscriptions.unknown.costCents) > 0 ? `, with ${formatCents(Number(subscriptions.unknown.costCents))} in recorded charges` : ""}. They remain in the inference ledger.</p>}
|
||||
{subscriptionError && subscriptions && <p role="status" className="text-sm text-muted-foreground">Showing the last loaded API and subscription usage. Updates will resume automatically.</p>}
|
||||
{discoverSubscriptions.error && <div role="status" className="flex flex-wrap items-center gap-2 text-sm text-muted-foreground">
|
||||
<p>Connected accounts could not be checked. Existing subscription estimates are still shown.</p>
|
||||
{subscriptions?.canRefresh && <Button variant="outline" size="sm" disabled={discoverSubscriptions.isPending}
|
||||
onClick={() => discoverSubscriptions.mutate(companyId)}>Retry account check</Button>}
|
||||
</div>}
|
||||
{spendData?.summary.pricingComplete === false && (
|
||||
<div role="status" className="space-y-1 text-sm text-muted-foreground">
|
||||
{spendData.summary.unpricedEventCount > 0 && (
|
||||
@@ -704,14 +730,16 @@ export function Costs({
|
||||
{incidentMutation.error && <p role="alert" className="text-sm text-destructive">Could not update the budget. Check any pending runs or unpriced usage shown on this page, then try again.</p>}
|
||||
<Tabs value={mainTab} onValueChange={(value) => { setMainTab(value as typeof mainTab); setSearchParams(current => { const next = new URLSearchParams(current); next.set("tab", value); return next; }, { replace: true }); }}>
|
||||
{!lockTab ? (
|
||||
<TabsList variant="line" className="justify-start">
|
||||
<TabsTrigger value="overview">Overview</TabsTrigger>
|
||||
{!hideBudgetsTab ? <TabsTrigger value="budgets">Budgets</TabsTrigger> : null}
|
||||
<TabsTrigger value="providers">Providers</TabsTrigger>
|
||||
<TabsTrigger value="billers">Billers</TabsTrigger>
|
||||
<TabsTrigger value="finance">Finance</TabsTrigger>
|
||||
<TabsTrigger value="decisions">Decisions</TabsTrigger>
|
||||
</TabsList>
|
||||
<div className="max-w-full overflow-x-auto pb-2">
|
||||
<TabsList variant="line" className="justify-start">
|
||||
<TabsTrigger value="overview">Overview</TabsTrigger>
|
||||
{!hideBudgetsTab ? <TabsTrigger value="budgets">Budgets</TabsTrigger> : null}
|
||||
<TabsTrigger value="providers">Providers</TabsTrigger>
|
||||
<TabsTrigger value="billers">Billers</TabsTrigger>
|
||||
<TabsTrigger value="finance">Finance</TabsTrigger>
|
||||
<TabsTrigger value="decisions">Decisions</TabsTrigger>
|
||||
</TabsList>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<TabsContent value="decisions" className="mt-4">{showCustomPrompt ? <p className="text-sm text-muted-foreground">Select a start and end date to load data.</p> : <DecisionHistory companyId={companyId} from={from} to={to} />}</TabsContent>
|
||||
@@ -756,10 +784,7 @@ export function Costs({
|
||||
{row.agentStatus === "terminated" ? <StatusBadge status="terminated" /> : null}
|
||||
</div>
|
||||
<div className="text-right text-sm tabular-nums">
|
||||
<div className="flex flex-wrap items-center justify-end gap-2 font-medium">
|
||||
<span>{formatCents(row.costCents)}</span>
|
||||
<CostEstimateLabel eventCount={row.eventCount} estimatedEventCount={row.estimatedEventCount} />
|
||||
</div>
|
||||
<CostAmount costCents={row.costCents} eventCount={row.eventCount} estimatedEventCount={row.estimatedEventCount} />
|
||||
<div className="text-xs text-muted-foreground">
|
||||
in {formatTokens(row.inputTokens + row.cachedInputTokens)} ({formatTokens(row.cachedInputTokens)} cached) · out {formatTokens(row.outputTokens)}
|
||||
</div>
|
||||
@@ -796,13 +821,12 @@ export function Costs({
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-right tabular-nums">
|
||||
<div className="flex flex-wrap items-center justify-end gap-2 font-medium">
|
||||
<span>
|
||||
{formatCents(modelRow.costCents)}
|
||||
<span className="ml-1 font-normal text-muted-foreground">({sharePct}%)</span>
|
||||
</span>
|
||||
<CostEstimateLabel eventCount={modelRow.eventCount} estimatedEventCount={modelRow.estimatedEventCount} />
|
||||
</div>
|
||||
<CostAmount
|
||||
costCents={modelRow.costCents}
|
||||
eventCount={modelRow.eventCount}
|
||||
estimatedEventCount={modelRow.estimatedEventCount}
|
||||
suffix={<span className="ml-1 font-normal text-muted-foreground">({sharePct}%)</span>}
|
||||
/>
|
||||
<div className="text-muted-foreground">
|
||||
{formatTokens(modelRow.inputTokens + modelRow.cachedInputTokens + modelRow.outputTokens)} tok
|
||||
</div>
|
||||
@@ -841,7 +865,7 @@ export function Costs({
|
||||
className="flex items-center justify-between gap-3 border border-border px-3 py-2 text-sm"
|
||||
>
|
||||
<span className="truncate">{row.projectName ?? row.projectId ?? "Unattributed"}</span>
|
||||
<span className="font-medium tabular-nums">{formatCents(row.costCents)}</span>
|
||||
<CostAmount costCents={row.costCents} eventCount={row.eventCount} estimatedEventCount={row.estimatedEventCount} />
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
import { useLayoutEffect, useState } from "react";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import { expect, userEvent, within } from "storybook/test";
|
||||
import { monthlySubscriptionCents, type SubscriptionCostReport } from "@paperclipai/shared";
|
||||
import { Costs } from "@/pages/Costs";
|
||||
|
||||
function fixture(): SubscriptionCostReport {
|
||||
const zero = { inputTokens: 0, cachedInputTokens: 0, outputTokens: 0, costCents: "0", eventCount: 0, estimatedEventCount: 0, unpricedEventCount: 0 };
|
||||
const price = { revision: 0, plan: "ChatGPT Plus", amountCents: "2000", monthlyCents: "2000", currency: "USD", cadence: "month" as const, status: "active" as const, source: "catalog" as const, sourceUrl: "https://learn.chatgpt.com/docs/pricing", effectiveAt: "2026-10-08T00:00:00Z" };
|
||||
return { canRefresh: true, asOf: new Date().toISOString(), activeCount: 2, unknownPriceCount: 0, unidentifiedAccountCount: 0,
|
||||
monthlyTotals: [{ currency: "USD", amountCents: "12000", estimatedCount: 2 }],
|
||||
api: { ...zero, costCents: "4217", inputTokens: 6000000, cachedInputTokens: 6200000, outputTokens: 200000, eventCount: 24, estimatedEventCount: 12 },
|
||||
subscription: { ...zero, inputTokens: 10000000, cachedInputTokens: 74000000, outputTokens: 1100000, eventCount: 50 },
|
||||
unknown: { ...zero }, unattributedSubscription: { ...zero },
|
||||
accounts: [
|
||||
{ id: "plus", provider: "openai", name: "Goldie’s ChatGPT", ownerUserId: "goldie", ownerName: "Goldie", shared: false, identityVerified: true,
|
||||
detectedPlan: "plus", observedAt: new Date().toISOString(), lastCheckedAt: new Date().toISOString(), refreshStatus: "ok", canEdit: true,
|
||||
price, usage: { ...zero, inputTokens: 8000000, cachedInputTokens: 60000000, outputTokens: 1000000, eventCount: 40 }, agents: [{ id: "codie", name: "Codie" }, { id: "fry", name: "Fry" }] },
|
||||
{ id: "max", provider: "anthropic", name: "Shared Claude", ownerUserId: null, ownerName: null, shared: true, identityVerified: true,
|
||||
detectedPlan: "max_5x", observedAt: new Date().toISOString(), lastCheckedAt: new Date().toISOString(), refreshStatus: "ok", canEdit: true,
|
||||
price: { ...price, plan: "Claude Max 5x", amountCents: "10000", monthlyCents: "10000", sourceUrl: "https://claude.com/pricing" },
|
||||
usage: { ...zero, inputTokens: 2000000, cachedInputTokens: 14000000, outputTokens: 100000, eventCount: 10 }, agents: [{ id: "leela", name: "Leela" }] },
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
/** Production Costs page; only API responses are fixtures. Edits persist in the story. */
|
||||
function SubscriptionCostsStory({ unknownPrice = false, stale = false }: { unknownPrice?: boolean; stale?: boolean }) {
|
||||
const [ready, setReady] = useState(false);
|
||||
const client = useQueryClient();
|
||||
useLayoutEffect(() => {
|
||||
const original = window.fetch;
|
||||
const report = fixture();
|
||||
if (unknownPrice) {
|
||||
report.accounts[1].price = { ...report.accounts[1].price, plan: "Claude Max", amountCents: null, monthlyCents: null, source: "unknown", sourceUrl: null };
|
||||
report.accounts[1].detectedPlan = "max";
|
||||
report.unknownPriceCount = 1; report.monthlyTotals = [{ currency: "USD", amountCents: "2000", estimatedCount: 1 }];
|
||||
}
|
||||
if (stale) report.accounts.forEach(account => { account.refreshStatus = "unavailable"; account.observedAt = "2026-10-06T10:00:00Z"; });
|
||||
window.fetch = async (input, init) => {
|
||||
const url = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url, window.location.origin);
|
||||
const base = "/api/companies/company-storybook/";
|
||||
const path = url.pathname.startsWith(base) ? url.pathname.slice(base.length) : "";
|
||||
if (path === "costs/subscriptions/refresh") return Response.json({ status: "accepted" }, { status: 202 });
|
||||
if (path === "costs/subscriptions") return Response.json(report);
|
||||
if (path.startsWith("costs/subscriptions/") && init?.method === "PATCH") {
|
||||
const account = report.accounts.find(row => row.id === path.split("/")[2])!;
|
||||
const patch = JSON.parse(String(init.body));
|
||||
account.price = { ...account.price, ...patch, source: "user", sourceUrl: null, revision: account.price.revision + 1,
|
||||
monthlyCents: patch.amountCents == null ? null : monthlySubscriptionCents(patch.amountCents, patch.cadence), effectiveAt: new Date().toISOString() };
|
||||
report.monthlyTotals = [];
|
||||
report.activeCount = 0; report.unknownPriceCount = 0;
|
||||
for (const row of report.accounts) {
|
||||
if (row.price.status !== "active") continue;
|
||||
report.activeCount++;
|
||||
if (row.price.monthlyCents == null) { report.unknownPriceCount++; continue; }
|
||||
let total = report.monthlyTotals.find(total => total.currency === row.price.currency);
|
||||
if (!total) report.monthlyTotals.push(total = { currency: row.price.currency, amountCents: "0", estimatedCount: 0 });
|
||||
total.amountCents = String(Number(total.amountCents) + Number(row.price.monthlyCents));
|
||||
total.estimatedCount += row.price.source === "catalog" ? 1 : 0;
|
||||
}
|
||||
return Response.json({ id: account.id });
|
||||
}
|
||||
if (path === "budgets/overview") return Response.json({ policies: [], activeIncidents: [], pausedAgentCount: 0, pausedProjectCount: 0, pendingApprovalCount: 0 });
|
||||
if (path === "costs/summary") return Response.json({ spendCents: 4217, budgetCents: 20000, utilizationPercent: 21, pricingComplete: true, eventCount: 74, estimatedEventCount: 12, unpricedEventCount: 0, pendingRunCount: 0 });
|
||||
if (path === "costs/by-agent") return Response.json([
|
||||
{ agentId: "codie", agentName: "Codie", agentStatus: "active", costCents: 4217, inputTokens: 12000000, cachedInputTokens: 56200000, outputTokens: 1000000, eventCount: 54, estimatedEventCount: 12, apiRunCount: 24, subscriptionRunCount: 30 },
|
||||
{ agentId: "fry", agentName: "Fry", agentStatus: "active", costCents: 0, inputTokens: 2000000, cachedInputTokens: 10000000, outputTokens: 200000, eventCount: 10, estimatedEventCount: 0, apiRunCount: 0, subscriptionRunCount: 10 },
|
||||
{ agentId: "leela", agentName: "Leela", agentStatus: "active", costCents: 0, inputTokens: 2000000, cachedInputTokens: 14000000, outputTokens: 100000, eventCount: 10, estimatedEventCount: 0, apiRunCount: 0, subscriptionRunCount: 10 },
|
||||
]);
|
||||
if (path === "costs/by-user") return Response.json({ activeUserCount: 1, rows: [{ userId: "goldie", userName: "Goldie", userImage: null, costCents: 4217, costCentsExact: "4217", inputTokens: 16000000, cachedInputTokens: 80200000, outputTokens: 1300000, eventCount: 74, estimatedEventCount: 12, unpricedEventCount: 0, runCount: 74 }] });
|
||||
if (path === "costs/by-project") return Response.json([{ projectId: "costs-project", projectName: "Cost reporting", costCents: 4217, inputTokens: 16000000, cachedInputTokens: 80200000, outputTokens: 1300000, eventCount: 74, estimatedEventCount: 12 }]);
|
||||
if (path === "costs/finance-summary") return Response.json({ netCents: 0, debitCents: 0, creditCents: 0, estimatedDebitCents: 0, eventCount: 0, currencies: [] });
|
||||
if (path.startsWith("costs/")) return Response.json([]);
|
||||
return original(input, init);
|
||||
};
|
||||
client.removeQueries({ queryKey: ["cost-subscriptions"] }); setReady(true);
|
||||
return () => { window.fetch = original; client.removeQueries({ queryKey: ["cost-subscriptions"] }); };
|
||||
}, [client, unknownPrice, stale]);
|
||||
return ready ? <Costs embedded hideBudgetsTab /> : null;
|
||||
}
|
||||
|
||||
const meta = { title: "Costs/Subscriptions", component: SubscriptionCostsStory, parameters: {
|
||||
layout: "padded", docs: { description: { component: "Production Costs page with API spend, monthly subscription estimates, user and project costs. View details to edit monthly or annual prices. Provider calls are fixtures." } },
|
||||
} } satisfies Meta<typeof SubscriptionCostsStory>;
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof meta>;
|
||||
export const Overview: Story = { play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await expect(await canvas.findByText("API spend")).toBeVisible();
|
||||
await expect(await canvas.findByText("$120.00")).toBeVisible();
|
||||
} };
|
||||
export const AccountDetails: Story = { play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await userEvent.click(await canvas.findByRole("button", { name: "View details" }));
|
||||
const dialog = within(document.body);
|
||||
await expect(await dialog.findByText("Goldie’s ChatGPT")).toBeVisible();
|
||||
await expect(await dialog.findByText("Used by Codie, Fry")).toBeVisible();
|
||||
} };
|
||||
export const UnknownPrice: Story = { args: { unknownPrice: true } };
|
||||
export const ProviderUnavailable: Story = { args: { stale: true } };
|
||||
export const Mobile: Story = { globals: { viewport: { value: "mobile1", isRotated: false } } };
|
||||
@@ -40,6 +40,13 @@ function Journey({ alreadyConfigured = false }: { alreadyConfigured?: boolean })
|
||||
const costBase = `/api/companies/${companyId}/costs/`;
|
||||
if (url.pathname.startsWith(costBase)) {
|
||||
const report = url.pathname.slice(costBase.length);
|
||||
if (report === "subscriptions") {
|
||||
const usage = { inputTokens: 0, cachedInputTokens: 0, outputTokens: 0, costCents: "0", eventCount: 0, estimatedEventCount: 0, unpricedEventCount: 0 };
|
||||
return Response.json({ canRefresh: false, asOf: new Date().toISOString(), accounts: [], monthlyTotals: [],
|
||||
activeCount: 0, unknownPriceCount: 0, unidentifiedAccountCount: 0,
|
||||
api: { ...usage, costCents: String(history.length * Number(entry.costCents)), eventCount: history.length, estimatedEventCount: history.length },
|
||||
subscription: usage, unknown: usage, unattributedSubscription: usage });
|
||||
}
|
||||
if (report === "summary") return Response.json({ companyId, eventCount: history.length, pendingRunCount: 0,
|
||||
unpricedEventCount: 0, estimatedEventCount: history.length, pricingComplete: true,
|
||||
spendCents: history.length * Number(entry.costCents), budgetCents: 0, utilizationPercent: 0 });
|
||||
|
||||
@@ -36,7 +36,7 @@ export function ExternalAgentInvitePreview({
|
||||
useEffect(() => {
|
||||
if (!simulate || !watching || connection.problem || connection.phase === "ready") return;
|
||||
const phase = connection.phase;
|
||||
const next = { waiting: "connected", connected: "subscribed", subscribed: "testing", testing: "ready" } as const;
|
||||
const next = { waiting: "connected", connected: "subscribed", subscribed: "testing", testing: "finishing", finishing: "ready" } as const;
|
||||
const timer = window.setTimeout(() => {
|
||||
setConnection(phase === "testing" && failTest && !retrying
|
||||
? { phase, problem: "event_timeout" } : { phase: next[phase] });
|
||||
|
||||
@@ -20,7 +20,18 @@ export const ChooseAgent: Story = { name: "Choose · Dot, Hermes, or Other", arg
|
||||
export const GivePromptToDot: Story = { name: "Dot · Copy and send the prompt", args: { initialScreen: "setup" } };
|
||||
export const WatchingDotConnect: Story = { name: "Dot · Watching task updates", args: { initialScreen: "setup", initialConnection: { phase: "connected" }, simulate: false } };
|
||||
export const ConfirmingRoundTrip: Story = { name: "Dot · Confirming the round trip", args: { initialScreen: "setup", initialConnection: { phase: "testing" }, simulate: false } };
|
||||
export const FinishingAgentSetup: Story = {
|
||||
name: "Dot · Finishing agent setup",
|
||||
args: { initialScreen: "setup", initialConnection: { phase: "finishing" }, simulate: false },
|
||||
play: async ({ canvasElement }) => {
|
||||
const page = within(canvasElement.ownerDocument.body);
|
||||
await expect(page.getByText("Test event confirmed", { exact: false })).toHaveTextContent("complete");
|
||||
await expect(page.getByRole("button", { name: "Finishing setup…" })).toBeDisabled();
|
||||
await expect(page.queryByRole("button", { name: "Done" })).not.toBeInTheDocument();
|
||||
},
|
||||
};
|
||||
export const DotReady: Story = { name: "Dot · Ready for tasks", args: { initialScreen: "setup", initialConnection: { phase: "ready" } } };
|
||||
export const PausedAgent: Story = { name: "Recovery · Connected agent paused", args: { initialScreen: "setup", initialConnection: { phase: "ready", problem: "agent_unavailable" }, simulate: false } };
|
||||
export const RetryEvent: Story = { name: "Recovery · Retry the test event", args: { initialScreen: "setup", initialConnection: { phase: "testing", problem: "event_timeout" } } };
|
||||
export const RefreshingPrompt: Story = { name: "Setup · Preparing a fresh prompt automatically", args: { initialScreen: "setup", preparing: true, simulate: false } };
|
||||
export const WatchingInterrupted: Story = { name: "Recovery · Connection updates interrupted", args: { initialScreen: "setup", initialConnection: { phase: "connected", problem: "offline" } } };
|
||||
|
||||
Reference in new issue
Block a user