diff --git a/apps/api/src/app/api/trpc/[trpc]/route.ts b/apps/api/src/app/api/trpc/[trpc]/route.ts index 3e9d9d83bdb..a6474b196a5 100644 --- a/apps/api/src/app/api/trpc/[trpc]/route.ts +++ b/apps/api/src/app/api/trpc/[trpc]/route.ts @@ -2,6 +2,9 @@ import { appRouter } from "@superset/trpc"; import { fetchRequestHandler } from "@trpc/server/adapters/fetch"; import { createContext } from "@/trpc/context"; +const LEADERBOARD_CACHE_SECONDS = 300; +const STATS_CACHE_SECONDS = 3600; + export const maxDuration = 60; const handler = (req: Request) => @@ -10,11 +13,37 @@ const handler = (req: Request) => req, router: appRouter, createContext, + // Anonymous leaderboard reads are the only cacheable surface here; every + // other procedure varies by session. Cache only when *every* path in the + // batch is under leaderboard.public, or a session-varying response gets + // served from the CDN to the next caller. + responseMeta: ({ paths, type, errors }) => { + if (type !== "query" || errors.length > 0 || !paths?.length) return {}; + if (!paths.every((path) => path.startsWith("leaderboard.public."))) { + return {}; + } + const maxAge = paths.every((path) => path === "leaderboard.public.stats") + ? STATS_CACHE_SECONDS + : LEADERBOARD_CACHE_SECONDS; + return { + headers: { + "cache-control": `public, s-maxage=${maxAge}, stale-while-revalidate=86400`, + vary: "origin", + }, + }; + }, onError: ({ path, error }) => { - // Suppress NOT_FOUND only for the known-dead device.heartbeat path - // (removed in #4490). Old desktop clients gated behind UpdateRequiredPage - // still call it; all other NOT_FOUND errors should remain visible. - if (error.code === "NOT_FOUND" && path === "device.heartbeat") return; + // Suppress NOT_FOUND for the known-dead device.heartbeat path (removed in + // #4490, old desktop clients gated behind UpdateRequiredPage still call + // it) and for public profile lookups, where an unknown handle is normal + // crawler traffic. All other NOT_FOUND errors should remain visible. + if ( + error.code === "NOT_FOUND" && + (path === "device.heartbeat" || + path === "leaderboard.public.participant") + ) { + return; + } console.error(`❌ tRPC error on ${path ?? ""}:`, error); }, }); diff --git a/apps/api/src/env.ts b/apps/api/src/env.ts index 003e9b54e6f..e196256ba43 100644 --- a/apps/api/src/env.ts +++ b/apps/api/src/env.ts @@ -82,6 +82,7 @@ export const env = createEnv({ NEXT_PUBLIC_API_URL: z.string().url(), NEXT_PUBLIC_WEB_URL: z.string().url(), NEXT_PUBLIC_ADMIN_URL: z.string().url(), + NEXT_PUBLIC_MARKETING_URL: z.string().url(), NEXT_PUBLIC_DESKTOP_URL: z.string().url().optional(), NEXT_PUBLIC_POSTHOG_KEY: z.string().min(1), NEXT_PUBLIC_POSTHOG_HOST: z.string().url(), @@ -95,6 +96,7 @@ export const env = createEnv({ NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL, NEXT_PUBLIC_WEB_URL: process.env.NEXT_PUBLIC_WEB_URL, NEXT_PUBLIC_ADMIN_URL: process.env.NEXT_PUBLIC_ADMIN_URL, + NEXT_PUBLIC_MARKETING_URL: process.env.NEXT_PUBLIC_MARKETING_URL, NEXT_PUBLIC_DESKTOP_URL: process.env.NEXT_PUBLIC_DESKTOP_URL, NEXT_PUBLIC_POSTHOG_KEY: process.env.NEXT_PUBLIC_POSTHOG_KEY, NEXT_PUBLIC_POSTHOG_HOST: process.env.NEXT_PUBLIC_POSTHOG_HOST, diff --git a/apps/api/src/proxy.ts b/apps/api/src/proxy.ts index 727a49765ce..b53ecfcefae 100644 --- a/apps/api/src/proxy.ts +++ b/apps/api/src/proxy.ts @@ -17,6 +17,7 @@ function getAllowedOrigins(deploymentOrigin: string) { return [ env.NEXT_PUBLIC_WEB_URL, env.NEXT_PUBLIC_ADMIN_URL, + env.NEXT_PUBLIC_MARKETING_URL, env.NEXT_PUBLIC_DESKTOP_URL, ...getTrustedVercelPreviewOrigins(deploymentOrigin), ...desktopDevOrigins, diff --git a/apps/desktop/src/renderer/components/LeaderboardJoinDialog/LeaderboardJoinDialog.tsx b/apps/desktop/src/renderer/components/LeaderboardJoinDialog/LeaderboardJoinDialog.tsx new file mode 100644 index 00000000000..99bf2806498 --- /dev/null +++ b/apps/desktop/src/renderer/components/LeaderboardJoinDialog/LeaderboardJoinDialog.tsx @@ -0,0 +1,107 @@ +import { Button } from "@superset/ui/button"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@superset/ui/dialog"; +import { Input } from "@superset/ui/input"; +import { Label } from "@superset/ui/label"; +import { useEffect, useState } from "react"; +import { RankTeaser } from "./components/RankTeaser"; +import type { LeaderboardPreview } from "./types"; + +const HANDLE_PATTERN = /^[a-z0-9](?:[a-z0-9]|-(?=[a-z0-9])){1,38}$/; + +interface LeaderboardJoinDialogProps { + open: boolean; + onOpenChange: (open: boolean) => void; + preview: LeaderboardPreview | null; + suggestedHandle: string | null; + isLoading: boolean; + isJoining: boolean; + onConfirm: (handle: string) => void; +} + +export function LeaderboardJoinDialog({ + open, + onOpenChange, + preview, + suggestedHandle, + isLoading, + isJoining, + onConfirm, +}: LeaderboardJoinDialogProps) { + const [handle, setHandle] = useState(""); + const [edited, setEdited] = useState(false); + + useEffect(() => { + if (!edited && suggestedHandle) setHandle(suggestedHandle); + }, [edited, suggestedHandle]); + + const trimmed = handle.trim().toLowerCase(); + const valid = HANDLE_PATTERN.test(trimmed); + + return ( + + + + Join the leaderboard + + Publishes your token counts and model names, never repo names, file + paths or prompts. You can leave at any time, which deletes + everything you've published. + + + +
+ {isLoading ? ( +

+ Reading your local usage… +

+ ) : preview ? ( + + ) : null} + +
+ + { + setEdited(true); + setHandle(event.target.value); + }} + placeholder="pick a name for the board" + autoComplete="off" + spellCheck={false} + /> +

+ Shown publicly alongside your name. +

+
+
+ + + + + +
+
+ ); +} diff --git a/apps/desktop/src/renderer/components/LeaderboardJoinDialog/components/RankTeaser/RankTeaser.tsx b/apps/desktop/src/renderer/components/LeaderboardJoinDialog/components/RankTeaser/RankTeaser.tsx new file mode 100644 index 00000000000..4f004b752f5 --- /dev/null +++ b/apps/desktop/src/renderer/components/LeaderboardJoinDialog/components/RankTeaser/RankTeaser.tsx @@ -0,0 +1,33 @@ +import { formatTokens } from "@superset/shared/format-tokens"; +import type { LeaderboardPreview } from "../../types"; + +const MIN_PARTICIPANTS_FOR_RANK = 50; + +export function RankTeaser({ preview }: { preview: LeaderboardPreview }) { + if (preview.tokens === 0) { + return ( +

+ No Claude or Codex usage found on this machine yet. Join now and you'll + appear once you've used an agent. +

+ ); + } + + return ( +
+ {preview.total >= MIN_PARTICIPANTS_FOR_RANK ? ( +

+ You'd be{" "} + #{preview.rank}{" "} + of {preview.total}. +

+ ) : ( +

You'd be one of the first on the board.

+ )} +

+ Based on {formatTokens(preview.tokens)} tokens in the last 30 days, + counting {preview.providers.join(" and ")}. +

+
+ ); +} diff --git a/apps/desktop/src/renderer/components/LeaderboardJoinDialog/components/RankTeaser/index.ts b/apps/desktop/src/renderer/components/LeaderboardJoinDialog/components/RankTeaser/index.ts new file mode 100644 index 00000000000..23eba9211fa --- /dev/null +++ b/apps/desktop/src/renderer/components/LeaderboardJoinDialog/components/RankTeaser/index.ts @@ -0,0 +1 @@ +export { RankTeaser } from "./RankTeaser"; diff --git a/apps/desktop/src/renderer/components/LeaderboardJoinDialog/index.ts b/apps/desktop/src/renderer/components/LeaderboardJoinDialog/index.ts new file mode 100644 index 00000000000..93ab73061bb --- /dev/null +++ b/apps/desktop/src/renderer/components/LeaderboardJoinDialog/index.ts @@ -0,0 +1,2 @@ +export { LeaderboardJoinDialog } from "./LeaderboardJoinDialog"; +export type { LeaderboardPreview } from "./types"; diff --git a/apps/desktop/src/renderer/components/LeaderboardJoinDialog/types.ts b/apps/desktop/src/renderer/components/LeaderboardJoinDialog/types.ts new file mode 100644 index 00000000000..800dd7de32b --- /dev/null +++ b/apps/desktop/src/renderer/components/LeaderboardJoinDialog/types.ts @@ -0,0 +1,9 @@ +import type { RouterOutputs } from "@superset/trpc"; + +export type LeaderboardPreview = Pick< + RouterOutputs["leaderboard"]["previewRank"], + "rank" | "total" +> & { + tokens: number; + providers: string[]; +}; diff --git a/apps/desktop/src/renderer/lib/leaderboard/askedState.test.ts b/apps/desktop/src/renderer/lib/leaderboard/askedState.test.ts new file mode 100644 index 00000000000..f7c87fa8212 --- /dev/null +++ b/apps/desktop/src/renderer/lib/leaderboard/askedState.test.ts @@ -0,0 +1,65 @@ +import { afterAll, beforeEach, describe, expect, it } from "bun:test"; +import { markLeaderboardAsked, readLeaderboardAsked } from "./askedState"; + +const originalLocalStorage = Object.getOwnPropertyDescriptor( + globalThis, + "localStorage", +); + +function installStorage(): void { + const entries = new Map(); + Object.defineProperty(globalThis, "localStorage", { + configurable: true, + writable: true, + value: { + getItem: (key: string) => entries.get(key) ?? null, + setItem: (key: string, value: string) => { + entries.set(key, value); + }, + removeItem: (key: string) => { + entries.delete(key); + }, + clear: () => entries.clear(), + key: (index: number) => [...entries.keys()][index] ?? null, + get length() { + return entries.size; + }, + } satisfies Storage, + }); +} + +beforeEach(installStorage); + +afterAll(() => { + if (originalLocalStorage) { + Object.defineProperty(globalThis, "localStorage", originalLocalStorage); + } else { + Reflect.deleteProperty(globalThis, "localStorage"); + } +}); + +describe("leaderboard asked flag", () => { + it("reports not asked on a fresh profile", () => { + expect(readLeaderboardAsked()).toBe(false); + }); + + it("round-trips through markLeaderboardAsked", () => { + markLeaderboardAsked(); + expect(readLeaderboardAsked()).toBe(true); + }); + + it("treats an unrecognised value as not asked", () => { + localStorage.setItem("leaderboard-asked-v1", "{}"); + expect(readLeaderboardAsked()).toBe(false); + }); + + it("suppresses the prompt when storage is unavailable", () => { + Object.defineProperty(globalThis, "localStorage", { + configurable: true, + get() { + throw new Error("denied"); + }, + }); + expect(readLeaderboardAsked()).toBe(true); + }); +}); diff --git a/apps/desktop/src/renderer/lib/leaderboard/askedState.ts b/apps/desktop/src/renderer/lib/leaderboard/askedState.ts new file mode 100644 index 00000000000..4571782d427 --- /dev/null +++ b/apps/desktop/src/renderer/lib/leaderboard/askedState.ts @@ -0,0 +1,17 @@ +const STORAGE_KEY = "leaderboard-asked-v1"; + +export function readLeaderboardAsked(): boolean { + try { + return localStorage.getItem(STORAGE_KEY) === "true"; + } catch { + return true; + } +} + +export function markLeaderboardAsked(): void { + try { + localStorage.setItem(STORAGE_KEY, "true"); + } catch { + return; + } +} diff --git a/apps/desktop/src/renderer/lib/leaderboard/index.ts b/apps/desktop/src/renderer/lib/leaderboard/index.ts new file mode 100644 index 00000000000..4fd24451624 --- /dev/null +++ b/apps/desktop/src/renderer/lib/leaderboard/index.ts @@ -0,0 +1,13 @@ +export { markLeaderboardAsked, readLeaderboardAsked } from "./askedState"; +export type { + LeaderboardFactoryDay, + LeaderboardPayload, + LeaderboardPayloadDay, +} from "./publishUsage"; +export { + BACKFILL_DAYS, + buildPayload, + PREVIEW_DAYS, + publishPayload, + publishUsage, +} from "./publishUsage"; diff --git a/apps/desktop/src/renderer/lib/leaderboard/publishUsage.ts b/apps/desktop/src/renderer/lib/leaderboard/publishUsage.ts new file mode 100644 index 00000000000..b899d32680b --- /dev/null +++ b/apps/desktop/src/renderer/lib/leaderboard/publishUsage.ts @@ -0,0 +1,53 @@ +import type { RouterInputs } from "@superset/trpc"; +import { PUBLISH_PAYLOAD_VERSION } from "@superset/trpc/leaderboard-schema"; +import { apiTrpcClient } from "renderer/lib/api-trpc-client"; +import { getHostServiceClientByUrl } from "renderer/lib/host-service-client"; + +export const BACKFILL_DAYS = 30; + +export const PREVIEW_DAYS = 30; + +type PublishInput = RouterInputs["leaderboard"]["publish"]; + +export type LeaderboardPayloadDay = PublishInput["days"][number]; +export type LeaderboardFactoryDay = NonNullable< + PublishInput["factoryDays"] +>[number]; + +export interface LeaderboardPayload { + days: LeaderboardPayloadDay[]; + factoryDays: LeaderboardFactoryDay[]; +} + +export async function buildPayload( + hostUrl: string, + days: number, +): Promise { + return await getHostServiceClientByUrl( + hostUrl, + ).usage.leaderboardPayload.query({ days }); +} + +export async function publishPayload( + machineId: string, + payload: LeaderboardPayload, +): Promise<{ written: number; days: number }> { + if (payload.days.length === 0 && payload.factoryDays.length === 0) { + return { written: 0, days: 0 }; + } + + return await apiTrpcClient.leaderboard.publish.mutate({ + payloadVersion: PUBLISH_PAYLOAD_VERSION, + hostId: machineId, + days: payload.days, + factoryDays: payload.factoryDays, + }); +} + +export async function publishUsage( + hostUrl: string, + machineId: string, + days: number = BACKFILL_DAYS, +): Promise<{ written: number; days: number }> { + return await publishPayload(machineId, await buildPayload(hostUrl, days)); +} diff --git a/apps/desktop/src/renderer/lib/persisted-keys/persisted-key-registry.test-data.ts b/apps/desktop/src/renderer/lib/persisted-keys/persisted-key-registry.test-data.ts index 811b1da1dfe..d9896c30ebf 100644 --- a/apps/desktop/src/renderer/lib/persisted-keys/persisted-key-registry.test-data.ts +++ b/apps/desktop/src/renderer/lib/persisted-keys/persisted-key-registry.test-data.ts @@ -142,6 +142,11 @@ export const PERSISTED_KEY_REGISTRY: ReadonlyArray< "src/renderer/components/PostHogUserIdentifier/PostHogUserIdentifier.tsx", ["active_organization_id"], ], + [ + "src/renderer/routes/_authenticated/components/LeaderboardAutoPublish/hooks/useLeaderboardAutoPublish/autoPublishState.ts", + ["leaderboard-auto-publish-v1"], + ], + ["src/renderer/lib/leaderboard/askedState.ts", ["leaderboard-asked-v1"]], [ "src/renderer/hooks/useAgentModelPreference/useAgentModelPreference.ts", ["lastSelectedV2WorkspaceCreateModelByPreset"], diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/components/LeaderboardPrompt/LeaderboardPrompt.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/components/LeaderboardPrompt/LeaderboardPrompt.tsx new file mode 100644 index 00000000000..daf32737430 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/components/LeaderboardPrompt/LeaderboardPrompt.tsx @@ -0,0 +1,66 @@ +import { Button } from "@superset/ui/button"; +import { TrophyIcon, XIcon } from "lucide-react"; +import { useState } from "react"; +import { LeaderboardJoinDialog } from "renderer/components/LeaderboardJoinDialog"; +import { useLeaderboardJoinPreview } from "renderer/routes/_authenticated/hooks/useLeaderboardJoinPreview"; +import { useLeaderboardOptIn } from "renderer/routes/_authenticated/hooks/useLeaderboardOptIn"; + +export function LeaderboardPrompt({ hostUrl }: { hostUrl: string | null }) { + const { isLoading, optedIn, join, joining } = useLeaderboardOptIn(); + const { + preview, + suggestedHandle, + isLoading: previewLoading, + load, + } = useLeaderboardJoinPreview(hostUrl); + + const [dismissed, setDismissed] = useState(false); + const [open, setOpen] = useState(false); + + if (isLoading || optedIn || dismissed) return null; + + const openJoin = () => { + setOpen(true); + void load(); + }; + + return ( + <> +
+ +
+

Compare this with everyone else

+

+ Publish token counts and model names to the public leaderboard. No + repo names, file paths or prompts. Leave any time. +

+
+
+ + +
+
+ + { + if (await join(handle)) setOpen(false); + }} + /> + + ); +} diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/components/LeaderboardPrompt/index.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/components/LeaderboardPrompt/index.ts new file mode 100644 index 00000000000..70d2616cce3 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/components/LeaderboardPrompt/index.ts @@ -0,0 +1 @@ +export { LeaderboardPrompt } from "./LeaderboardPrompt"; diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/components/UsageHistorySection/utils/formatUsage/formatUsage.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/components/UsageHistorySection/utils/formatUsage/formatUsage.ts index 45fa6bea4f5..31555939438 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/components/UsageHistorySection/utils/formatUsage/formatUsage.ts +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/components/UsageHistorySection/utils/formatUsage/formatUsage.ts @@ -1,3 +1,5 @@ +export { formatTokens } from "@superset/shared/format-tokens"; + /** "$19,211", "$46.20", "$0.85" — whole dollars once past $100. */ export function formatUsd(usd: number): string { if (usd >= 100) { @@ -6,14 +8,6 @@ export function formatUsd(usd: number): string { return `$${usd.toFixed(2)}`; } -/** "13.9B", "4.2M", "850K", "312" */ -export function formatTokens(tokens: number): string { - if (tokens >= 1e9) return `${(tokens / 1e9).toFixed(1)}B`; - if (tokens >= 1e6) return `${(tokens / 1e6).toFixed(1)}M`; - if (tokens >= 1e3) return `${Math.round(tokens / 1e3)}K`; - return String(Math.round(tokens)); -} - /** "Aug 12" from a `YYYY-MM-DD` bucket key. */ export function formatDayLabel(day: string): string { const [year, month, date] = day.split("-").map(Number); diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/components/UsageView/UsageView.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/components/UsageView/UsageView.tsx index 843383817fc..5683fa6ed1c 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/components/UsageView/UsageView.tsx +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/usage/components/UsageView/UsageView.tsx @@ -29,6 +29,7 @@ import type { import { useHostUsageQuota } from "../../hooks/useHostUsageQuota"; import { useRemoveUsageAccount } from "../../hooks/useRemoveUsageAccount"; import { useSetDefaultUsageAccount } from "../../hooks/useSetDefaultUsageAccount"; +import { LeaderboardPrompt } from "../LeaderboardPrompt"; import { UsageHistorySection } from "../UsageHistorySection"; import type { SwitchSignInTarget } from "./components/AddAccountDialog"; import { AddAccountDialog } from "./components/AddAccountDialog"; @@ -308,6 +309,7 @@ export function UsageView({ hostUrl }: { hostUrl: string | null }) { return (
+
Official quota · refreshes every 5 min diff --git a/apps/desktop/src/renderer/routes/_authenticated/components/LeaderboardAutoPublish/LeaderboardAutoPublish.tsx b/apps/desktop/src/renderer/routes/_authenticated/components/LeaderboardAutoPublish/LeaderboardAutoPublish.tsx new file mode 100644 index 00000000000..b2372072a8a --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/components/LeaderboardAutoPublish/LeaderboardAutoPublish.tsx @@ -0,0 +1,6 @@ +import { useLeaderboardAutoPublish } from "./hooks/useLeaderboardAutoPublish"; + +export function LeaderboardAutoPublish() { + useLeaderboardAutoPublish(); + return null; +} diff --git a/apps/desktop/src/renderer/routes/_authenticated/components/LeaderboardAutoPublish/hooks/useLeaderboardAutoPublish/autoPublishSchedule.test.ts b/apps/desktop/src/renderer/routes/_authenticated/components/LeaderboardAutoPublish/hooks/useLeaderboardAutoPublish/autoPublishSchedule.test.ts new file mode 100644 index 00000000000..cab25ec4362 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/components/LeaderboardAutoPublish/hooks/useLeaderboardAutoPublish/autoPublishSchedule.test.ts @@ -0,0 +1,129 @@ +import { describe, expect, it } from "bun:test"; +import { + hashPayload, + isPublishDue, + PUBLISH_INTERVAL_MS, + publishWindowDays, +} from "./autoPublishSchedule"; + +const HOUR = 60 * 60 * 1000; +const DAY = 24 * HOUR; +const NOW = 1_800_000_000_000; + +describe("isPublishDue", () => { + it("holds off until the two-hour deadline passes", () => { + const state = { + handle: "me", + lastPublishedAt: NOW - HOUR, + lastPayloadHash: "a", + }; + expect(isPublishDue(state, NOW)).toBe(false); + }); + + it("fires once the deadline is reached", () => { + const state = { + handle: "me", + lastPublishedAt: NOW - PUBLISH_INTERVAL_MS, + lastPayloadHash: "a", + }; + expect(isPublishDue(state, NOW)).toBe(true); + }); + + it("fires on a machine that has never published", () => { + expect( + isPublishDue( + { handle: "me", lastPublishedAt: 0, lastPayloadHash: null }, + NOW, + ), + ).toBe(true); + }); + + it("fires when a clock change puts the last publish in the future", () => { + const state = { + handle: "me", + lastPublishedAt: NOW + 10 * DAY, + lastPayloadHash: "a", + }; + expect(isPublishDue(state, NOW)).toBe(true); + }); +}); + +describe("publishWindowDays", () => { + it("backfills the full window on a first publish", () => { + expect( + publishWindowDays( + { handle: "me", lastPublishedAt: 0, lastPayloadHash: null }, + NOW, + ), + ).toBe(30); + }); + + it("uses the two-day floor in steady state", () => { + const state = { + handle: "me", + lastPublishedAt: NOW - PUBLISH_INTERVAL_MS, + lastPayloadHash: "a", + }; + expect(publishWindowDays(state, NOW)).toBe(2); + }); + + it("widens to cover a gap the app was closed for", () => { + const state = { + handle: "me", + lastPublishedAt: NOW - 6 * DAY, + lastPayloadHash: "a", + }; + expect(publishWindowDays(state, NOW)).toBe(7); + }); + + it("clamps a very long absence to the backfill ceiling", () => { + const state = { + handle: "me", + lastPublishedAt: NOW - 400 * DAY, + lastPayloadHash: "a", + }; + expect(publishWindowDays(state, NOW)).toBe(30); + }); + + it("never returns less than the floor when the clock moved backwards", () => { + const state = { + handle: "me", + lastPublishedAt: NOW + 5 * DAY, + lastPayloadHash: "a", + }; + expect(publishWindowDays(state, NOW)).toBe(2); + }); +}); + +describe("hashPayload", () => { + it("matches for identical payloads", () => { + const payload = { + days: [{ day: "2026-08-25", model: "opus", output: 10 }], + factoryDays: [{ day: "2026-08-25", sessions: 3 }], + }; + expect(hashPayload(payload)).toBe(hashPayload(structuredClone(payload))); + }); + + it("differs when a token count changes", () => { + expect(hashPayload({ days: [{ output: 10 }], factoryDays: [] })).not.toBe( + hashPayload({ days: [{ output: 11 }], factoryDays: [] }), + ); + }); + + it("differs when a day is added", () => { + expect( + hashPayload({ days: [{ day: "2026-08-25" }], factoryDays: [] }), + ).not.toBe( + hashPayload({ + days: [{ day: "2026-08-25" }, { day: "2026-08-24" }], + factoryDays: [], + }), + ); + }); + + it("differs when only factoryDays changed", () => { + expect( + hashPayload({ days: [], factoryDays: [{ agentPrsMerged: 1 }] }), + ).not.toBe(hashPayload({ days: [], factoryDays: [{ agentPrsMerged: 2 }] })); + }); +}); diff --git a/apps/desktop/src/renderer/routes/_authenticated/components/LeaderboardAutoPublish/hooks/useLeaderboardAutoPublish/autoPublishSchedule.ts b/apps/desktop/src/renderer/routes/_authenticated/components/LeaderboardAutoPublish/hooks/useLeaderboardAutoPublish/autoPublishSchedule.ts new file mode 100644 index 00000000000..6acf6f1a1c8 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/components/LeaderboardAutoPublish/hooks/useLeaderboardAutoPublish/autoPublishSchedule.ts @@ -0,0 +1,55 @@ +export const PUBLISH_INTERVAL_MS = 2 * 60 * 60 * 1000; +export const CHECK_INTERVAL_MS = 5 * 60 * 1000; + +const DAY_MS = 24 * 60 * 60 * 1000; +const MIN_WINDOW_DAYS = 2; +const MAX_WINDOW_DAYS = 30; + +export interface AutoPublishState { + handle: string | null; + lastPublishedAt: number; + lastPayloadHash: string | null; +} + +export const INITIAL_AUTO_PUBLISH_STATE: AutoPublishState = { + handle: null, + lastPublishedAt: 0, + lastPayloadHash: null, +}; + +export function isPublishDue(state: AutoPublishState, now: number): boolean { + if (state.lastPublishedAt > now) return true; + return now - state.lastPublishedAt >= PUBLISH_INTERVAL_MS; +} + +export function publishWindowDays( + state: AutoPublishState, + now: number, +): number { + if (state.lastPublishedAt <= 0) return MAX_WINDOW_DAYS; + const elapsedDays = Math.ceil( + Math.max(0, now - state.lastPublishedAt) / DAY_MS, + ); + return Math.min(MAX_WINDOW_DAYS, Math.max(MIN_WINDOW_DAYS, elapsedDays + 1)); +} + +export function hashPayload(payload: { + days: readonly unknown[]; + factoryDays: readonly unknown[]; +}): string { + const serialized = JSON.stringify([payload.days, payload.factoryDays]); + let h1 = 0xdeadbeef; + let h2 = 0x41c6ce57; + for (let i = 0; i < serialized.length; i++) { + const ch = serialized.charCodeAt(i); + h1 = Math.imul(h1 ^ ch, 2654435761); + h2 = Math.imul(h2 ^ ch, 1597334677); + } + h1 = + Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ + Math.imul(h2 ^ (h2 >>> 13), 3266489909); + h2 = + Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ + Math.imul(h1 ^ (h1 >>> 13), 3266489909); + return `${(h2 >>> 0).toString(16)}${(h1 >>> 0).toString(16)}`; +} diff --git a/apps/desktop/src/renderer/routes/_authenticated/components/LeaderboardAutoPublish/hooks/useLeaderboardAutoPublish/autoPublishState.ts b/apps/desktop/src/renderer/routes/_authenticated/components/LeaderboardAutoPublish/hooks/useLeaderboardAutoPublish/autoPublishState.ts new file mode 100644 index 00000000000..686571dd3d6 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/components/LeaderboardAutoPublish/hooks/useLeaderboardAutoPublish/autoPublishState.ts @@ -0,0 +1,43 @@ +import type { AutoPublishState } from "./autoPublishSchedule"; +import { INITIAL_AUTO_PUBLISH_STATE } from "./autoPublishSchedule"; + +const STORAGE_KEY = "leaderboard-auto-publish-v1"; + +export function readAutoPublishState(handle: string): AutoPublishState { + try { + const raw = localStorage.getItem(STORAGE_KEY); + if (!raw) return INITIAL_AUTO_PUBLISH_STATE; + const parsed = JSON.parse(raw) as Partial; + if (parsed.handle !== handle) return INITIAL_AUTO_PUBLISH_STATE; + return { + handle, + lastPublishedAt: + typeof parsed.lastPublishedAt === "number" && + Number.isFinite(parsed.lastPublishedAt) + ? parsed.lastPublishedAt + : 0, + lastPayloadHash: + typeof parsed.lastPayloadHash === "string" + ? parsed.lastPayloadHash + : null, + }; + } catch { + return INITIAL_AUTO_PUBLISH_STATE; + } +} + +export function clearAutoPublishState(): void { + try { + localStorage.removeItem(STORAGE_KEY); + } catch { + return; + } +} + +export function writeAutoPublishState(state: AutoPublishState): void { + try { + localStorage.setItem(STORAGE_KEY, JSON.stringify(state)); + } catch { + return; + } +} diff --git a/apps/desktop/src/renderer/routes/_authenticated/components/LeaderboardAutoPublish/hooks/useLeaderboardAutoPublish/index.ts b/apps/desktop/src/renderer/routes/_authenticated/components/LeaderboardAutoPublish/hooks/useLeaderboardAutoPublish/index.ts new file mode 100644 index 00000000000..2a9a0c58f4c --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/components/LeaderboardAutoPublish/hooks/useLeaderboardAutoPublish/index.ts @@ -0,0 +1,8 @@ +export { + CHECK_INTERVAL_MS, + hashPayload, + isPublishDue, + PUBLISH_INTERVAL_MS, + publishWindowDays, +} from "./autoPublishSchedule"; +export { useLeaderboardAutoPublish } from "./useLeaderboardAutoPublish"; diff --git a/apps/desktop/src/renderer/routes/_authenticated/components/LeaderboardAutoPublish/hooks/useLeaderboardAutoPublish/useLeaderboardAutoPublish.ts b/apps/desktop/src/renderer/routes/_authenticated/components/LeaderboardAutoPublish/hooks/useLeaderboardAutoPublish/useLeaderboardAutoPublish.ts new file mode 100644 index 00000000000..ec44f6cd036 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/components/LeaderboardAutoPublish/hooks/useLeaderboardAutoPublish/useLeaderboardAutoPublish.ts @@ -0,0 +1,68 @@ +import { useCallback, useEffect, useRef } from "react"; +import { buildPayload, publishPayload } from "renderer/lib/leaderboard"; +import { useLeaderboardOptIn } from "renderer/routes/_authenticated/hooks/useLeaderboardOptIn"; +import { useLocalHostService } from "renderer/routes/_authenticated/providers/LocalHostServiceProvider"; +import { + CHECK_INTERVAL_MS, + hashPayload, + isPublishDue, + publishWindowDays, +} from "./autoPublishSchedule"; +import { + readAutoPublishState, + writeAutoPublishState, +} from "./autoPublishState"; + +export function useLeaderboardAutoPublish(): void { + const { activeHostUrl, machineId } = useLocalHostService(); + const { handle } = useLeaderboardOptIn(); + const inFlight = useRef(false); + + const maybePublish = useCallback(async () => { + if (!handle || !activeHostUrl || !machineId) return; + if (inFlight.current) return; + + const state = readAutoPublishState(handle); + const now = Date.now(); + if (!isPublishDue(state, now)) return; + + inFlight.current = true; + try { + const payload = await buildPayload( + activeHostUrl, + publishWindowDays(state, now), + ); + const hash = hashPayload(payload); + if (hash !== state.lastPayloadHash) { + await publishPayload(machineId, payload); + } + writeAutoPublishState({ + handle, + lastPublishedAt: Date.now(), + lastPayloadHash: hash, + }); + } catch (error) { + console.warn("[leaderboard] auto-publish failed (will retry):", error); + } finally { + inFlight.current = false; + } + }, [handle, activeHostUrl, machineId]); + + useEffect(() => { + if (!handle || !activeHostUrl || !machineId) return; + + void maybePublish(); + const timer = setInterval(() => void maybePublish(), CHECK_INTERVAL_MS); + const onVisibility = () => { + if (!document.hidden) void maybePublish(); + }; + document.addEventListener("visibilitychange", onVisibility); + window.addEventListener("focus", onVisibility); + + return () => { + clearInterval(timer); + document.removeEventListener("visibilitychange", onVisibility); + window.removeEventListener("focus", onVisibility); + }; + }, [handle, activeHostUrl, machineId, maybePublish]); +} diff --git a/apps/desktop/src/renderer/routes/_authenticated/components/LeaderboardAutoPublish/index.ts b/apps/desktop/src/renderer/routes/_authenticated/components/LeaderboardAutoPublish/index.ts new file mode 100644 index 00000000000..b82c310bf96 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/components/LeaderboardAutoPublish/index.ts @@ -0,0 +1 @@ +export { LeaderboardAutoPublish } from "./LeaderboardAutoPublish"; diff --git a/apps/desktop/src/renderer/routes/_authenticated/components/LeaderboardFirstRunDialog/LeaderboardFirstRunDialog.tsx b/apps/desktop/src/renderer/routes/_authenticated/components/LeaderboardFirstRunDialog/LeaderboardFirstRunDialog.tsx new file mode 100644 index 00000000000..3b6bd1ad481 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/components/LeaderboardFirstRunDialog/LeaderboardFirstRunDialog.tsx @@ -0,0 +1,50 @@ +import { useEffect, useState } from "react"; +import { LeaderboardJoinDialog } from "renderer/components/LeaderboardJoinDialog"; +import { authClient } from "renderer/lib/auth-client"; +import { + markLeaderboardAsked, + readLeaderboardAsked, +} from "renderer/lib/leaderboard"; +import { useLeaderboardJoinPreview } from "renderer/routes/_authenticated/hooks/useLeaderboardJoinPreview"; +import { useLeaderboardOptIn } from "renderer/routes/_authenticated/hooks/useLeaderboardOptIn"; +import { useLocalHostService } from "renderer/routes/_authenticated/providers/LocalHostServiceProvider"; + +export function LeaderboardFirstRunDialog() { + const { data: session } = authClient.useSession(); + const { activeHostUrl } = useLocalHostService(); + const { isLoading, optedIn, join, joining } = useLeaderboardOptIn(); + const { + preview, + suggestedHandle, + isLoading: previewLoading, + load, + } = useLeaderboardJoinPreview(activeHostUrl); + + const [asked, setAsked] = useState(readLeaderboardAsked); + const [open, setOpen] = useState(false); + + const onboarded = Boolean(session?.user?.onboardedAt); + + useEffect(() => { + if (asked || !onboarded || isLoading || optedIn) return; + + markLeaderboardAsked(); + setAsked(true); + setOpen(true); + void load(); + }, [asked, onboarded, isLoading, optedIn, load]); + + return ( + { + if (await join(handle)) setOpen(false); + }} + /> + ); +} diff --git a/apps/desktop/src/renderer/routes/_authenticated/components/LeaderboardFirstRunDialog/index.ts b/apps/desktop/src/renderer/routes/_authenticated/components/LeaderboardFirstRunDialog/index.ts new file mode 100644 index 00000000000..cea691ffab8 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/components/LeaderboardFirstRunDialog/index.ts @@ -0,0 +1 @@ +export { LeaderboardFirstRunDialog } from "./LeaderboardFirstRunDialog"; diff --git a/apps/desktop/src/renderer/routes/_authenticated/hooks/useLeaderboardJoinPreview/index.ts b/apps/desktop/src/renderer/routes/_authenticated/hooks/useLeaderboardJoinPreview/index.ts new file mode 100644 index 00000000000..6f07ccf4035 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/hooks/useLeaderboardJoinPreview/index.ts @@ -0,0 +1 @@ +export { useLeaderboardJoinPreview } from "./useLeaderboardJoinPreview"; diff --git a/apps/desktop/src/renderer/routes/_authenticated/hooks/useLeaderboardJoinPreview/useLeaderboardJoinPreview.ts b/apps/desktop/src/renderer/routes/_authenticated/hooks/useLeaderboardJoinPreview/useLeaderboardJoinPreview.ts new file mode 100644 index 00000000000..20f086f3ed6 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/hooks/useLeaderboardJoinPreview/useLeaderboardJoinPreview.ts @@ -0,0 +1,57 @@ +import { toast } from "@superset/ui/sonner"; +import { useCallback, useState } from "react"; +import type { LeaderboardPreview } from "renderer/components/LeaderboardJoinDialog"; +import { apiTrpcClient } from "renderer/lib/api-trpc-client"; +import { buildPayload, PREVIEW_DAYS } from "renderer/lib/leaderboard"; + +const FALLBACK_PROVIDERS = ["Claude", "Codex"]; + +export function useLeaderboardJoinPreview(hostUrl: string | null) { + const [preview, setPreview] = useState(null); + const [suggestedHandle, setSuggestedHandle] = useState(null); + const [isLoading, setIsLoading] = useState(false); + + const load = useCallback(async () => { + setIsLoading(true); + try { + const [suggestion, payload] = await Promise.all([ + apiTrpcClient.leaderboard.suggestedHandle.query(), + hostUrl + ? buildPayload(hostUrl, PREVIEW_DAYS) + : Promise.resolve({ days: [] }), + ]); + setSuggestedHandle(suggestion.taken ? null : suggestion.handle); + + const tokens = payload.days.reduce( + (sum, day) => + sum + + day.uncachedInput + + day.cachedInput + + day.cacheWrite5m + + day.cacheWrite1h + + day.output, + 0, + ); + const providers = [...new Set(payload.days.map((day) => day.provider))]; + const rank = await apiTrpcClient.leaderboard.previewRank.query({ + period: "30d", + tokens, + }); + + setPreview({ + rank: rank.rank, + total: rank.total, + tokens, + providers: providers.length > 0 ? providers : FALLBACK_PROVIDERS, + }); + } catch (error) { + toast.error( + error instanceof Error ? error.message : "Couldn't read local usage", + ); + } finally { + setIsLoading(false); + } + }, [hostUrl]); + + return { preview, suggestedHandle, isLoading, load }; +} diff --git a/apps/desktop/src/renderer/routes/_authenticated/hooks/useLeaderboardOptIn/index.ts b/apps/desktop/src/renderer/routes/_authenticated/hooks/useLeaderboardOptIn/index.ts new file mode 100644 index 00000000000..f22405c9e52 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/hooks/useLeaderboardOptIn/index.ts @@ -0,0 +1 @@ +export { useLeaderboardOptIn } from "./useLeaderboardOptIn"; diff --git a/apps/desktop/src/renderer/routes/_authenticated/hooks/useLeaderboardOptIn/useLeaderboardOptIn.ts b/apps/desktop/src/renderer/routes/_authenticated/hooks/useLeaderboardOptIn/useLeaderboardOptIn.ts new file mode 100644 index 00000000000..0b5b1207fc0 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/hooks/useLeaderboardOptIn/useLeaderboardOptIn.ts @@ -0,0 +1,101 @@ +import { toast } from "@superset/ui/sonner"; +import { useQuery } from "@tanstack/react-query"; +import { useCallback, useState } from "react"; +import { apiTrpcClient } from "renderer/lib/api-trpc-client"; +import { BACKFILL_DAYS, publishUsage } from "renderer/lib/leaderboard"; +import { + clearAutoPublishState, + writeAutoPublishState, +} from "renderer/routes/_authenticated/components/LeaderboardAutoPublish/hooks/useLeaderboardAutoPublish/autoPublishState"; +import { useLocalHostService } from "renderer/routes/_authenticated/providers/LocalHostServiceProvider"; + +export function useLeaderboardOptIn() { + const { activeHostUrl, machineId } = useLocalHostService(); + + const membership = useQuery({ + queryKey: ["leaderboard", "me"] as const, + queryFn: () => apiTrpcClient.leaderboard.me.query({ period: "all" }), + staleTime: 60_000, + retry: false, + }); + + const [joining, setJoining] = useState(false); + const [leaving, setLeaving] = useState(false); + + const join = useCallback( + async (handle: string) => { + setJoining(true); + try { + try { + await apiTrpcClient.leaderboard.join.mutate({ + handle, + visibility: "public", + }); + } catch (error) { + toast.error(error instanceof Error ? error.message : "Couldn't join"); + return false; + } + + let published: number | null = 0; + if (activeHostUrl && machineId) { + try { + published = ( + await publishUsage(activeHostUrl, machineId, BACKFILL_DAYS) + ).days; + writeAutoPublishState({ + handle, + lastPublishedAt: Date.now(), + lastPayloadHash: null, + }); + } catch { + published = null; + } + } + + await membership.refetch(); + + if (published === null) { + toast.success(`Joined as ${handle}`); + toast.error("Couldn't publish your usage yet — it'll retry shortly"); + } else { + toast.success( + published > 0 + ? `Joined as ${handle} — published ${published} ${published === 1 ? "day" : "days"}` + : `Joined as ${handle}`, + ); + } + return true; + } finally { + setJoining(false); + } + }, + [activeHostUrl, machineId, membership], + ); + + const leave = useCallback(async () => { + setLeaving(true); + try { + await apiTrpcClient.leaderboard.leave.mutate(); + clearAutoPublishState(); + await membership.refetch(); + toast.success("Left the leaderboard and deleted your published usage"); + return true; + } catch (error) { + toast.error(error instanceof Error ? error.message : "Couldn't leave"); + return false; + } finally { + setLeaving(false); + } + }, [membership]); + + return { + membership: membership.data ?? null, + handle: membership.data?.handle ?? null, + optedIn: Boolean(membership.data), + isLoading: membership.isLoading, + join, + leave, + joining, + leaving, + }; +} diff --git a/apps/desktop/src/renderer/routes/_authenticated/layout.tsx b/apps/desktop/src/renderer/routes/_authenticated/layout.tsx index f85a08fd7e0..9fd5cea436e 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/layout.tsx +++ b/apps/desktop/src/renderer/routes/_authenticated/layout.tsx @@ -28,6 +28,8 @@ import { InitGitDialog } from "renderer/react-query/projects/InitGitDialog"; import { DaemonAutoUpdateFailureDialog } from "renderer/routes/_authenticated/components/DaemonAutoUpdateFailureDialog"; import { DashboardNewWorkspaceModal } from "renderer/routes/_authenticated/components/DashboardNewWorkspaceModal"; import { DiffThemeSync } from "renderer/routes/_authenticated/components/DiffThemeSync"; +import { LeaderboardAutoPublish } from "renderer/routes/_authenticated/components/LeaderboardAutoPublish"; +import { LeaderboardFirstRunDialog } from "renderer/routes/_authenticated/components/LeaderboardFirstRunDialog"; import { PendingDeletionScreen } from "renderer/routes/_authenticated/components/PendingDeletionScreen"; import { StarNagObserver } from "renderer/routes/_authenticated/components/StarNagObserver"; import { @@ -304,6 +306,8 @@ function AuthenticatedLayout() { + + diff --git a/apps/desktop/src/renderer/routes/_authenticated/settings/account/components/AccountSettings/AccountSettings.tsx b/apps/desktop/src/renderer/routes/_authenticated/settings/account/components/AccountSettings/AccountSettings.tsx index 610bad92d1f..297624b910d 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/settings/account/components/AccountSettings/AccountSettings.tsx +++ b/apps/desktop/src/renderer/routes/_authenticated/settings/account/components/AccountSettings/AccountSettings.tsx @@ -30,6 +30,7 @@ import { SETTING_ITEM_ID, type SettingItemId, } from "../../../utils/settings-search"; +import { LeaderboardSection } from "./components/LeaderboardSection"; import { ProfileSkeleton } from "./components/ProfileSkeleton"; interface AccountSettingsProps { @@ -49,6 +50,10 @@ export function AccountSettings({ visibleItems }: AccountSettingsProps) { SETTING_ITEM_ID.ACCOUNT_DELETE, visibleItems, ); + const showLeaderboard = isItemVisible( + SETTING_ITEM_ID.ACCOUNT_LEADERBOARD, + visibleItems, + ); const { data: session, @@ -201,6 +206,12 @@ export function AccountSettings({ visibleItems }: AccountSettingsProps) {
)} + {showLeaderboard && ( +
+ +
+ )} + {showDelete && (
diff --git a/apps/desktop/src/renderer/routes/_authenticated/settings/account/components/AccountSettings/components/LeaderboardSection/LeaderboardSection.tsx b/apps/desktop/src/renderer/routes/_authenticated/settings/account/components/AccountSettings/components/LeaderboardSection/LeaderboardSection.tsx new file mode 100644 index 00000000000..4b7e59cbcf9 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/settings/account/components/AccountSettings/components/LeaderboardSection/LeaderboardSection.tsx @@ -0,0 +1,111 @@ +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from "@superset/ui/alert-dialog"; +import { Label } from "@superset/ui/label"; +import { Switch } from "@superset/ui/switch"; +import { useState } from "react"; +import { LeaderboardJoinDialog } from "renderer/components/LeaderboardJoinDialog"; +import { useLeaderboardJoinPreview } from "renderer/routes/_authenticated/hooks/useLeaderboardJoinPreview"; +import { useLeaderboardOptIn } from "renderer/routes/_authenticated/hooks/useLeaderboardOptIn"; +import { useLocalHostService } from "renderer/routes/_authenticated/providers/LocalHostServiceProvider"; +import { HighlightText } from "renderer/routes/_authenticated/settings/components/HighlightText"; +import { useSettingsSearchQuery } from "renderer/stores/settings-state"; + +export function LeaderboardSection() { + const searchQuery = useSettingsSearchQuery(); + const { activeHostUrl } = useLocalHostService(); + const { handle, isLoading, optedIn, join, leave, joining } = + useLeaderboardOptIn(); + + const { + preview, + suggestedHandle, + isLoading: previewLoading, + load, + } = useLeaderboardJoinPreview(activeHostUrl); + + const [joinOpen, setJoinOpen] = useState(false); + const [leaveOpen, setLeaveOpen] = useState(false); + + const openJoin = () => { + setJoinOpen(true); + void load(); + }; + + return ( + <> +
+
+ +

+ {optedIn && handle ? ( + <> + Publishing as {handle}. + Token counts and model names only, no repo names, file paths or + prompts. + + ) : ( + <> + Rank your agent usage against other engineers. Token counts and + model names only, no repo names, file paths or prompts. + + )} +

+
+ { + if (next) openJoin(); + else setLeaveOpen(true); + }} + /> +
+ + { + if (await join(handle)) setJoinOpen(false); + }} + /> + + + + + Leave the leaderboard? + + Everything you've published is deleted, not hidden. You can rejoin + later and it will rebuild from the transcripts still on this + machine — only your past ranking is lost. + + + + Cancel + { + if (await leave()) setLeaveOpen(false); + }} + > + Leave and delete + + + + + + ); +} diff --git a/apps/desktop/src/renderer/routes/_authenticated/settings/account/components/AccountSettings/components/LeaderboardSection/index.ts b/apps/desktop/src/renderer/routes/_authenticated/settings/account/components/AccountSettings/components/LeaderboardSection/index.ts new file mode 100644 index 00000000000..bba4cfe3698 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/settings/account/components/AccountSettings/components/LeaderboardSection/index.ts @@ -0,0 +1 @@ +export { LeaderboardSection } from "./LeaderboardSection"; diff --git a/apps/desktop/src/renderer/routes/_authenticated/settings/utils/settings-search/settings-search.ts b/apps/desktop/src/renderer/routes/_authenticated/settings/utils/settings-search/settings-search.ts index d13fdcd10e5..6867532d474 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/settings/utils/settings-search/settings-search.ts +++ b/apps/desktop/src/renderer/routes/_authenticated/settings/utils/settings-search/settings-search.ts @@ -8,6 +8,7 @@ export const SETTING_ITEM_ID = { ACCOUNT_PROFILE: "account-profile", ACCOUNT_SIGNOUT: "account-signout", ACCOUNT_DELETE: "account-delete", + ACCOUNT_LEADERBOARD: "account-leaderboard", ORGANIZATION_LOGO: "organization-logo", ORGANIZATION_NAME: "organization-name", @@ -145,6 +146,7 @@ export const SETTING_ITEM_VARIANT: Record = { [SETTING_ITEM_ID.ACCOUNT_PROFILE]: "shared", [SETTING_ITEM_ID.ACCOUNT_SIGNOUT]: "shared", [SETTING_ITEM_ID.ACCOUNT_DELETE]: "shared", + [SETTING_ITEM_ID.ACCOUNT_LEADERBOARD]: "shared", [SETTING_ITEM_ID.ORGANIZATION_LOGO]: "shared", [SETTING_ITEM_ID.ORGANIZATION_NAME]: "shared", @@ -362,6 +364,24 @@ export const SETTINGS_ITEMS: SettingsItem[] = [ "erase", ], }, + { + id: SETTING_ITEM_ID.ACCOUNT_LEADERBOARD, + section: "account", + title: "Leaderboard", + description: "Publish your agent usage to the public leaderboard", + keywords: [ + "leaderboard", + "rank", + "ranking", + "public", + "share", + "usage", + "tokens", + "stats", + "opt in", + "opt out", + ], + }, { id: SETTING_ITEM_ID.ORGANIZATION_LOGO, section: "organization", diff --git a/apps/marketing/package.json b/apps/marketing/package.json index bc13007b7f9..b591dce507d 100644 --- a/apps/marketing/package.json +++ b/apps/marketing/package.json @@ -19,10 +19,13 @@ "@superset/auth": "workspace:*", "@superset/email": "workspace:*", "@superset/shared": "workspace:*", + "@superset/trpc": "workspace:*", "@superset/ui": "workspace:*", "@t3-oss/env-nextjs": "0.13.11", + "@trpc/client": "11.16.0", "@upstash/ratelimit": "2.0.8", "@upstash/redis": "1.37.0", + "date-fns": "4.1.0", "framer-motion": "12.38.0", "geist": "1.7.0", "gray-matter": "4.0.3", @@ -45,6 +48,7 @@ "shiki": "3.23.0", "simplex-noise": "4.0.3", "stripe-gradient": "1.0.1", + "superjson": "2.2.6", "three": "0.181.2", "zod": "4.4.3" }, @@ -58,6 +62,7 @@ "@types/react-dom": "19.2.3", "@types/three": "0.181.0", "babel-plugin-react-compiler": "1.0.0", + "bun-types": "1.3.14", "dotenv": "17.3.1", "tailwindcss": "4.2.2", "typescript": "6.0.3" diff --git a/apps/marketing/src/app/components/ModelBars/ModelBars.tsx b/apps/marketing/src/app/components/ModelBars/ModelBars.tsx new file mode 100644 index 00000000000..5d21d36c942 --- /dev/null +++ b/apps/marketing/src/app/components/ModelBars/ModelBars.tsx @@ -0,0 +1,138 @@ +import { formatCount, formatTokens, formatUsd } from "../../utils/formatUsage"; + +const PALETTE = [ + "#d25611", + "#6b8ca3", + "#7a9e7e", + "#c19a5b", + "#9d7b9e", + "#5f8a8a", + "#b07d6a", + "#8a8a9e", + "#a3906b", + "#6e6e78", +]; + +export type ModelColors = Map; + +export function modelKey(provider: string, model: string): string { + return `${provider}/${model}`; +} + +export function buildModelColors( + lists: Array>, +): ModelColors { + const colors: ModelColors = new Map(); + for (const list of lists) { + for (const entry of list) { + const key = modelKey(entry.provider, entry.model); + if (!colors.has(key)) { + colors.set(key, PALETTE[colors.size % PALETTE.length] as string); + } + } + } + return colors; +} + +export interface ModelBarRow { + provider: string; + model: string; + value: number; + display: string; +} + +export function ModelBars({ + rows, + colors, +}: { + rows: ModelBarRow[]; + colors?: ModelColors; +}) { + if (rows.length === 0) { + return ( +

No usage in this range.

+ ); + } + + const max = Math.max(...rows.map((row) => row.value)); + + return ( +
+ {rows.map((row, index) => { + const color = + colors?.get(modelKey(row.provider, row.model)) ?? + (PALETTE[index % PALETTE.length] as string); + return ( +
+
+ + + + {row.model} + + + + {row.display} + +
+
+
0 ? (row.value / max) * 100 : 0}%`, + backgroundColor: color, + }} + /> +
+
+ ); + })} +
+ ); +} + +export function toUserRows( + models: Array<{ provider: string; model: string; users: number }>, +): ModelBarRow[] { + return models.map((model) => ({ + provider: model.provider, + model: model.model, + value: model.users, + display: `${formatCount(model.users)} dev${model.users === 1 ? "" : "s"}`, + })); +} + +export function toSpendRows( + models: Array<{ + provider: string; + model: string; + usd: string; + tokens: number; + }>, +): ModelBarRow[] { + return models.map((model) => ({ + provider: model.provider, + model: model.model, + value: Number.parseFloat(model.usd) || 0, + display: formatUsd(model.usd), + })); +} + +export function toTokenRows( + models: Array<{ + provider: string; + model: string; + usd: string; + tokens: number; + }>, +): ModelBarRow[] { + return models.map((model) => ({ + provider: model.provider, + model: model.model, + value: model.tokens, + display: formatTokens(model.tokens), + })); +} diff --git a/apps/marketing/src/app/components/ModelBars/index.ts b/apps/marketing/src/app/components/ModelBars/index.ts new file mode 100644 index 00000000000..2edadcf4e22 --- /dev/null +++ b/apps/marketing/src/app/components/ModelBars/index.ts @@ -0,0 +1,9 @@ +export type { ModelBarRow, ModelColors } from "./ModelBars"; +export { + buildModelColors, + ModelBars, + modelKey, + toSpendRows, + toTokenRows, + toUserRows, +} from "./ModelBars"; diff --git a/apps/marketing/src/app/components/StatStrip/StatStrip.tsx b/apps/marketing/src/app/components/StatStrip/StatStrip.tsx new file mode 100644 index 00000000000..4c74ccb37ac --- /dev/null +++ b/apps/marketing/src/app/components/StatStrip/StatStrip.tsx @@ -0,0 +1,35 @@ +interface Stat { + label: string; + value: string; + hint?: string; +} + +export function StatStrip({ + stats, + pixelClassName = "", +}: { + stats: Stat[]; + pixelClassName?: string; +}) { + return ( +
+ {stats.map((stat) => ( +
+
+ {stat.value} +
+
+ {stat.label} +
+ {stat.hint && ( +
+ {stat.hint} +
+ )} +
+ ))} +
+ ); +} diff --git a/apps/marketing/src/app/components/StatStrip/index.ts b/apps/marketing/src/app/components/StatStrip/index.ts new file mode 100644 index 00000000000..baf31eecde5 --- /dev/null +++ b/apps/marketing/src/app/components/StatStrip/index.ts @@ -0,0 +1 @@ +export { StatStrip } from "./StatStrip"; diff --git a/apps/marketing/src/app/components/TierBadge/TierBadge.tsx b/apps/marketing/src/app/components/TierBadge/TierBadge.tsx new file mode 100644 index 00000000000..001655d9903 --- /dev/null +++ b/apps/marketing/src/app/components/TierBadge/TierBadge.tsx @@ -0,0 +1,57 @@ +export const TIER_NAMES = [ + "Button pusher", + "Operator", + "Plant Manager", + "Henry Ford", +] as const; + +const TIER_STYLES = [ + "text-muted-foreground border-border", + "text-sky-400 border-sky-400/30", + "text-emerald-400 border-emerald-400/30", + "text-brand border-brand/40", +] as const; + +export const tierLabel = (tier: number): string => + tier >= 1 && tier <= 4 ? (TIER_NAMES[tier - 1] ?? "Unranked") : "Unranked"; + +interface TierBadgeProps { + tier: number; + + size?: "sm" | "hero"; + className?: string; +} + +export function TierBadge({ + tier, + size = "sm", + className = "", +}: TierBadgeProps) { + const ranked = tier >= 1 && tier <= 4; + const style = ranked + ? (TIER_STYLES[tier - 1] ?? TIER_STYLES[0]) + : "text-muted-foreground/60 border-border/60"; + + if (size === "hero") { + return ( +
+ + {ranked ? `Factory tier ${tier}` : "Unranked"} + + + {tierLabel(tier)} + +
+ ); + } + + return ( + + {tierLabel(tier)} + + ); +} diff --git a/apps/marketing/src/app/components/TierBadge/index.ts b/apps/marketing/src/app/components/TierBadge/index.ts new file mode 100644 index 00000000000..053b890649c --- /dev/null +++ b/apps/marketing/src/app/components/TierBadge/index.ts @@ -0,0 +1 @@ +export { TIER_NAMES, TierBadge, tierLabel } from "./TierBadge"; diff --git a/apps/marketing/src/app/components/TierTube/TierTube.tsx b/apps/marketing/src/app/components/TierTube/TierTube.tsx new file mode 100644 index 00000000000..491a39d3d68 --- /dev/null +++ b/apps/marketing/src/app/components/TierTube/TierTube.tsx @@ -0,0 +1,187 @@ +import { TIER_NAMES } from "@/app/components/TierBadge"; + +const ZONES = [ + { tier: 1, rgb: "138,144,153" }, + { tier: 2, rgb: "91,157,251" }, + { tier: 3, rgb: "63,207,127" }, + { tier: 4, rgb: "242,163,60" }, +] as const; + +const railLeft = (position: number) => + position <= 0 ? 0 : ((position - 0.5) / ZONES.length) * 100; + +const MONTHS_PER_TIER = 8; + +function forecastLabel(tier: number, position: number): string | null { + if (position <= 0) return null; + if (tier <= Math.floor(position)) return null; + + const months = Math.max(1, Math.round((tier - position) * MONTHS_PER_TIER)); + const when = new Date(); + when.setUTCDate(1); + when.setUTCMonth(when.getUTCMonth() + months); + return when.toLocaleDateString("en-US", { + month: "short", + year: "numeric", + timeZone: "UTC", + }); +} + +function PaceTooltip({ + reached, + forecast, + rgb, + className, +}: { + reached: boolean; + forecast: string | null; + rgb: string; + className: string; +}) { + return ( +
+
+
+ {reached ? "Reached" : "On this pace"} +
+
+ {reached ? "Now" : (forecast ?? "—")} +
+
+
+ ); +} + +interface TierTubeProps { + position: number; + counts?: number[]; + subject?: "fleet" | "you"; + pixelClassName?: string; +} + +export function TierTube({ + position, + counts, + subject = "you", + pixelClassName = "", +}: TierTubeProps) { + const activeTier = Math.min(4, Math.max(0, Math.floor(position))); + const active = ZONES.find((zone) => zone.tier === activeTier); + const travelled = railLeft(position); + const isFleet = subject === "fleet"; + const showPace = isFleet && position > 0; + + return ( +
+
+
+
+ + {active && ( +
+
+
+ )} +
+ + {ZONES.map(({ tier, rgb }) => { + const reached = tier <= activeTier; + const isActive = tier === activeTier; + return ( +
+ {showPace && ( + + )} + {/* Square, not a dot — it sits better next to the pixel face. */} +
+
+ ); + })} +
+ +
+ {ZONES.map(({ tier, rgb }) => { + const reached = tier <= activeTier; + const isActive = tier === activeTier; + const value = isFleet + ? counts + ? String(counts[tier] ?? 0) + : "—" + : isActive + ? "YOU" + : "—"; + return ( +
+ {showPace && ( + + )} +
+ {value} +
+
+ {TIER_NAMES[tier - 1]} +
+ {isFleet && counts && isActive && ( +
+ most developers +
+ )} +
+ ); + })} +
+
+ ); +} diff --git a/apps/marketing/src/app/components/TierTube/index.ts b/apps/marketing/src/app/components/TierTube/index.ts new file mode 100644 index 00000000000..2bf4f3fafe8 --- /dev/null +++ b/apps/marketing/src/app/components/TierTube/index.ts @@ -0,0 +1 @@ +export { TierTube } from "./TierTube"; diff --git a/apps/marketing/src/app/components/TokenSplitBar/TokenSplitBar.tsx b/apps/marketing/src/app/components/TokenSplitBar/TokenSplitBar.tsx new file mode 100644 index 00000000000..9114a72062b --- /dev/null +++ b/apps/marketing/src/app/components/TokenSplitBar/TokenSplitBar.tsx @@ -0,0 +1,65 @@ +import { formatTokens } from "../../utils/formatUsage"; + +interface Segment { + label: string; + tokens: number; + color: string; +} + +export function TokenSplitBar({ + split, +}: { + split: { + uncachedInput: number; + cachedInput: number; + cacheWrite5m: number; + cacheWrite1h: number; + output: number; + reasoningOutput: number; + }; +}) { + const segments: Segment[] = [ + { label: "Input", tokens: split.uncachedInput, color: "#d25611" }, + { label: "Output", tokens: split.output, color: "#c19a5b" }, + { label: "Cache read", tokens: split.cachedInput, color: "#6b8ca3" }, + { + label: "Cache write", + tokens: split.cacheWrite5m + split.cacheWrite1h, + color: "#7a9e7e", + }, + ]; + + const total = segments.reduce((sum, segment) => sum + segment.tokens, 0); + if (total === 0) { + return ( +

No usage in this range.

+ ); + } + + return ( +
+ {segments.map((segment) => { + const percent = (segment.tokens / total) * 100; + return ( +
+
+ {segment.label} + + {formatTokens(segment.tokens)} · {percent.toFixed(0)}% + +
+
+
0 ? 0.5 : 0)}%`, + backgroundColor: segment.color, + }} + /> +
+
+ ); + })} +
+ ); +} diff --git a/apps/marketing/src/app/components/TokenSplitBar/index.ts b/apps/marketing/src/app/components/TokenSplitBar/index.ts new file mode 100644 index 00000000000..706ede89c90 --- /dev/null +++ b/apps/marketing/src/app/components/TokenSplitBar/index.ts @@ -0,0 +1 @@ +export { TokenSplitBar } from "./TokenSplitBar"; diff --git a/apps/marketing/src/app/globals.css b/apps/marketing/src/app/globals.css index ae1e34d7ac0..a09fed39387 100644 --- a/apps/marketing/src/app/globals.css +++ b/apps/marketing/src/app/globals.css @@ -238,3 +238,45 @@ .blog-code-block .hidden.dark\:block { display: block; } + +@theme { + --animate-belt-march: belt-march 900ms linear infinite; + --animate-rail-extend: rail-extend 1100ms cubic-bezier(0.22, 1, 0.36, 1) both; + --animate-station-pulse: station-pulse 2.4s ease-in-out infinite; +} + +@keyframes belt-march { + from { + background-position-x: 0; + } + to { + background-position-x: 17px; + } +} + +@keyframes rail-extend { + from { + transform: scaleX(0); + } + to { + transform: scaleX(1); + } +} + +@keyframes station-pulse { + 0%, + 100% { + opacity: 1; + } + 50% { + opacity: 0.55; + } +} + +@media (prefers-reduced-motion: reduce) { + .animate-belt-march, + .animate-rail-extend, + .animate-station-pulse { + animation: none; + } +} diff --git a/apps/marketing/src/app/leaderboard/components/LeaderboardBoard/LeaderboardBoard.tsx b/apps/marketing/src/app/leaderboard/components/LeaderboardBoard/LeaderboardBoard.tsx new file mode 100644 index 00000000000..4ff5e44e3c8 --- /dev/null +++ b/apps/marketing/src/app/leaderboard/components/LeaderboardBoard/LeaderboardBoard.tsx @@ -0,0 +1,178 @@ +"use client"; + +import { useEffect, useRef, useState } from "react"; +import { StatStrip } from "@/app/components/StatStrip"; +import { TierTube } from "@/app/components/TierTube"; +import type { + LeaderboardMetric, + LeaderboardStats, + Standings, +} from "@/app/utils/fetchLeaderboard"; +import { fetchStandings, fetchStats } from "@/app/utils/fetchLeaderboard"; +import { + formatDayRange, + formatTokens, + formatUsd, +} from "@/app/utils/formatUsage"; +import { LeaderboardTable } from "./components/LeaderboardTable"; +import { MetricTabs } from "./components/MetricTabs"; +import { type RangeSelection, RangeTabs } from "./components/RangeTabs"; +import { buildStandingsQuery } from "./utils/buildStandingsQuery"; + +interface LeaderboardBoardProps { + initialStandings: Standings | null; + initialStats: LeaderboardStats | null; + earliest: string; + + pixelClassName?: string; +} + +const PAGE_SIZE = 50; + +export function LeaderboardBoard({ + initialStandings, + initialStats, + earliest, + pixelClassName, +}: LeaderboardBoardProps) { + const [metric, setMetric] = useState("tokens"); + const [selection, setSelection] = useState({ period: "30d" }); + const [standings, setStandings] = useState(initialStandings); + const [stats, setStats] = useState(initialStats); + const [loading, setLoading] = useState(false); + const [touched, setTouched] = useState(false); + const [loadingMore, setLoadingMore] = useState(false); + const queryGeneration = useRef(0); + + useEffect(() => { + if (!touched) return; + + const controller = new AbortController(); + setLoading(true); + + Promise.all([ + fetchStandings( + { ...buildStandingsQuery(selection, metric), limit: PAGE_SIZE }, + controller.signal, + ), + fetchStats(buildStandingsQuery(selection), controller.signal), + ]) + .then(([nextStandings, nextStats]) => { + if (nextStandings) setStandings(nextStandings); + if (nextStats) setStats(nextStats); + }) + .catch(() => {}) + .finally(() => setLoading(false)); + + return () => controller.abort(); + }, [metric, selection, touched]); + + const loadMore = async () => { + if (!standings || loadingMore) return; + const generation = queryGeneration.current; + setLoadingMore(true); + try { + const next = await fetchStandings({ + ...buildStandingsQuery(selection, metric), + limit: PAGE_SIZE, + offset: standings.rows.length, + }); + if (!next || generation !== queryGeneration.current) return; + setStandings({ + ...next, + rows: [...standings.rows, ...next.rows], + }); + } finally { + setLoadingMore(false); + } + }; + + const update = ( + next: Partial<{ metric: LeaderboardMetric; selection: RangeSelection }>, + ) => { + queryGeneration.current += 1; + setTouched(true); + if (next.metric) setMetric(next.metric); + if (next.selection) setSelection(next.selection); + }; + + const range = standings?.range ?? null; + const totals = stats?.totals; + + return ( +
+ + + {totals && ( + 0 + ? Math.round( + ((stats?.tokenSplit.cachedInput ?? 0) / totals.tokens) * + 100, + ) + : 0 + }%`, + hint: "of all tokens", + }, + ]} + /> + )} + +
+ update({ metric: next })} + /> + update({ selection: next })} + earliest={new Date(`${earliest}T00:00:00`)} + latest={new Date()} + /> + + {formatDayRange(range)} + +
+ + + + {standings && standings.total > standings.rows.length && ( +
+ + + {standings.rows.length} of {standings.total} + +
+ )} +
+ ); +} diff --git a/apps/marketing/src/app/leaderboard/components/LeaderboardBoard/components/LeaderboardTable/LeaderboardTable.tsx b/apps/marketing/src/app/leaderboard/components/LeaderboardBoard/components/LeaderboardTable/LeaderboardTable.tsx new file mode 100644 index 00000000000..fbccf72513f --- /dev/null +++ b/apps/marketing/src/app/leaderboard/components/LeaderboardBoard/components/LeaderboardTable/LeaderboardTable.tsx @@ -0,0 +1,134 @@ +import Link from "next/link"; +import { TierBadge } from "@/app/components/TierBadge"; +import type { + LeaderboardMetric, + StandingRow, +} from "@/app/utils/fetchLeaderboard"; +import { formatCount, formatTokens, formatUsd } from "@/app/utils/formatUsage"; +import { DeveloperAvatar } from "./components/DeveloperAvatar"; + +interface LeaderboardTableProps { + rows: StandingRow[]; + metric: LeaderboardMetric; + isLoading?: boolean; + + pixelClassName?: string; +} + +export function LeaderboardTable({ + rows, + metric, + isLoading, + pixelClassName = "", +}: LeaderboardTableProps) { + if (isLoading) { + return ( +
+ {["a", "b", "c", "d", "e", "f", "g", "h"].map((key) => ( +
+ ))} +
+ ); + } + + if (rows.length === 0) { + return ( +
+

+ Nobody has joined the board yet. +

+

+ Opt in from Superset under Settings → Account. +

+
+ ); + } + + return ( +
+ + + + + + + + + + + + {rows.map((row) => ( + + + + + + + + ))} + +
+ # + + Developer + + Tier + + Sessions + + {metric === "cost" ? "Cost" : "Tokens"} +
+ {row.rank} + + + +
+ {row.name ? ( + <> +
+ {row.name} +
+
+ @{row.handle} +
+ + ) : ( +
+ @{row.handle} +
+ )} +
+ +
+ + + {formatCount(row.sessions)} + + {metric === "cost" + ? formatUsd(row.usd) + : formatTokens(row.tokens)} + {row.approximate && ( + + * + + )} +
+
+ ); +} diff --git a/apps/marketing/src/app/leaderboard/components/LeaderboardBoard/components/LeaderboardTable/components/DeveloperAvatar/DeveloperAvatar.tsx b/apps/marketing/src/app/leaderboard/components/LeaderboardBoard/components/LeaderboardTable/components/DeveloperAvatar/DeveloperAvatar.tsx new file mode 100644 index 00000000000..c9c089d5c01 --- /dev/null +++ b/apps/marketing/src/app/leaderboard/components/LeaderboardBoard/components/LeaderboardTable/components/DeveloperAvatar/DeveloperAvatar.tsx @@ -0,0 +1,17 @@ +import Image from "next/image"; +import { avatarUrl } from "@/app/utils/avatarUrl"; + +const SIZE = 32; + +export function DeveloperAvatar({ handle }: { handle: string }) { + return ( + + ); +} diff --git a/apps/marketing/src/app/leaderboard/components/LeaderboardBoard/components/LeaderboardTable/components/DeveloperAvatar/index.ts b/apps/marketing/src/app/leaderboard/components/LeaderboardBoard/components/LeaderboardTable/components/DeveloperAvatar/index.ts new file mode 100644 index 00000000000..5a21fd6d52b --- /dev/null +++ b/apps/marketing/src/app/leaderboard/components/LeaderboardBoard/components/LeaderboardTable/components/DeveloperAvatar/index.ts @@ -0,0 +1 @@ +export { DeveloperAvatar } from "./DeveloperAvatar"; diff --git a/apps/marketing/src/app/leaderboard/components/LeaderboardBoard/components/LeaderboardTable/index.ts b/apps/marketing/src/app/leaderboard/components/LeaderboardBoard/components/LeaderboardTable/index.ts new file mode 100644 index 00000000000..a6fc8ce3d54 --- /dev/null +++ b/apps/marketing/src/app/leaderboard/components/LeaderboardBoard/components/LeaderboardTable/index.ts @@ -0,0 +1 @@ +export { LeaderboardTable } from "./LeaderboardTable"; diff --git a/apps/marketing/src/app/leaderboard/components/LeaderboardBoard/components/MetricTabs/MetricTabs.tsx b/apps/marketing/src/app/leaderboard/components/LeaderboardBoard/components/MetricTabs/MetricTabs.tsx new file mode 100644 index 00000000000..c877d606cea --- /dev/null +++ b/apps/marketing/src/app/leaderboard/components/LeaderboardBoard/components/MetricTabs/MetricTabs.tsx @@ -0,0 +1,25 @@ +"use client"; + +import type { LeaderboardMetric } from "@/app/utils/fetchLeaderboard"; +import { PillTabs } from "../PillTabs"; + +const METRICS: Array<{ id: LeaderboardMetric; label: string }> = [ + { id: "tokens", label: "Tokens" }, + { id: "cost", label: "Cost" }, +]; + +interface MetricTabsProps { + value: LeaderboardMetric; + onChange: (metric: LeaderboardMetric) => void; +} + +export function MetricTabs({ value, onChange }: MetricTabsProps) { + return ( + + ); +} diff --git a/apps/marketing/src/app/leaderboard/components/LeaderboardBoard/components/MetricTabs/index.ts b/apps/marketing/src/app/leaderboard/components/LeaderboardBoard/components/MetricTabs/index.ts new file mode 100644 index 00000000000..3e1106f92e9 --- /dev/null +++ b/apps/marketing/src/app/leaderboard/components/LeaderboardBoard/components/MetricTabs/index.ts @@ -0,0 +1 @@ +export { MetricTabs } from "./MetricTabs"; diff --git a/apps/marketing/src/app/leaderboard/components/LeaderboardBoard/components/PillTabs/PillTabs.tsx b/apps/marketing/src/app/leaderboard/components/LeaderboardBoard/components/PillTabs/PillTabs.tsx new file mode 100644 index 00000000000..4377bda46d1 --- /dev/null +++ b/apps/marketing/src/app/leaderboard/components/LeaderboardBoard/components/PillTabs/PillTabs.tsx @@ -0,0 +1,48 @@ +"use client"; + +import type { ReactNode } from "react"; + +interface PillTabsProps { + label: string; + value: T | null; + options: ReadonlyArray<{ id: T; label: string }>; + onChange: (id: T) => void; + children?: ReactNode; +} + +export function PillTabs({ + label, + value, + options, + onChange, + children, +}: PillTabsProps) { + return ( +
+ {options.map((option) => { + const active = option.id === value; + return ( + + ); + })} + {children} +
+ ); +} diff --git a/apps/marketing/src/app/leaderboard/components/LeaderboardBoard/components/PillTabs/index.ts b/apps/marketing/src/app/leaderboard/components/LeaderboardBoard/components/PillTabs/index.ts new file mode 100644 index 00000000000..179cb35e6af --- /dev/null +++ b/apps/marketing/src/app/leaderboard/components/LeaderboardBoard/components/PillTabs/index.ts @@ -0,0 +1 @@ +export { PillTabs } from "./PillTabs"; diff --git a/apps/marketing/src/app/leaderboard/components/LeaderboardBoard/components/RangeTabs/RangeTabs.tsx b/apps/marketing/src/app/leaderboard/components/LeaderboardBoard/components/RangeTabs/RangeTabs.tsx new file mode 100644 index 00000000000..55d81fd0815 --- /dev/null +++ b/apps/marketing/src/app/leaderboard/components/LeaderboardBoard/components/RangeTabs/RangeTabs.tsx @@ -0,0 +1,81 @@ +"use client"; + +import { Button } from "@superset/ui/button"; +import { Calendar } from "@superset/ui/calendar"; +import { Popover, PopoverContent, PopoverTrigger } from "@superset/ui/popover"; +import { CalendarIcon } from "lucide-react"; +import type { DateRange } from "react-day-picker"; +import type { LeaderboardPeriod } from "@/app/utils/fetchLeaderboard"; +import { formatRangeLabel } from "@/app/utils/formatRangeLabel"; +import { PillTabs } from "../PillTabs"; + +const PRESETS: Array<{ id: LeaderboardPeriod; label: string }> = [ + { id: "all", label: "All" }, + { id: "7d", label: "7D" }, + { id: "30d", label: "30D" }, +]; + +export interface RangeSelection { + period: LeaderboardPeriod; + custom?: DateRange; +} + +interface RangeTabsProps { + value: RangeSelection; + onChange: (selection: RangeSelection) => void; + earliest: Date; + latest: Date; +} + +export function RangeTabs({ + value, + onChange, + earliest, + latest, +}: RangeTabsProps) { + const customActive = Boolean(value.custom?.from && value.custom?.to); + + return ( + onChange({ period })} + > + + + + + + + onChange({ + period: value.period, + custom: range?.from && range?.to ? range : range, + }) + } + disabled={{ before: earliest, after: latest }} + /> + + + + ); +} diff --git a/apps/marketing/src/app/leaderboard/components/LeaderboardBoard/components/RangeTabs/index.ts b/apps/marketing/src/app/leaderboard/components/LeaderboardBoard/components/RangeTabs/index.ts new file mode 100644 index 00000000000..4ec038e57ce --- /dev/null +++ b/apps/marketing/src/app/leaderboard/components/LeaderboardBoard/components/RangeTabs/index.ts @@ -0,0 +1,2 @@ +export type { RangeSelection } from "./RangeTabs"; +export { RangeTabs } from "./RangeTabs"; diff --git a/apps/marketing/src/app/leaderboard/components/LeaderboardBoard/index.ts b/apps/marketing/src/app/leaderboard/components/LeaderboardBoard/index.ts new file mode 100644 index 00000000000..29e5bc7e6a9 --- /dev/null +++ b/apps/marketing/src/app/leaderboard/components/LeaderboardBoard/index.ts @@ -0,0 +1 @@ +export { LeaderboardBoard } from "./LeaderboardBoard"; diff --git a/apps/marketing/src/app/leaderboard/components/LeaderboardBoard/utils/buildStandingsQuery/buildStandingsQuery.ts b/apps/marketing/src/app/leaderboard/components/LeaderboardBoard/utils/buildStandingsQuery/buildStandingsQuery.ts new file mode 100644 index 00000000000..112753c71eb --- /dev/null +++ b/apps/marketing/src/app/leaderboard/components/LeaderboardBoard/utils/buildStandingsQuery/buildStandingsQuery.ts @@ -0,0 +1,18 @@ +import type { StandingsQuery } from "@/app/utils/fetchLeaderboard"; +import type { RangeSelection } from "../../components/RangeTabs"; + +function toDayKey(date: Date): string { + return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`; +} + +export function buildStandingsQuery( + selection: RangeSelection, + metric?: StandingsQuery["metric"], +): StandingsQuery { + const custom = selection.custom; + const range: StandingsQuery = + custom?.from && custom?.to + ? { from: toDayKey(custom.from), to: toDayKey(custom.to) } + : { period: selection.period }; + return metric ? { ...range, metric } : range; +} diff --git a/apps/marketing/src/app/leaderboard/components/LeaderboardBoard/utils/buildStandingsQuery/index.ts b/apps/marketing/src/app/leaderboard/components/LeaderboardBoard/utils/buildStandingsQuery/index.ts new file mode 100644 index 00000000000..8df6990a8f1 --- /dev/null +++ b/apps/marketing/src/app/leaderboard/components/LeaderboardBoard/utils/buildStandingsQuery/index.ts @@ -0,0 +1 @@ +export { buildStandingsQuery } from "./buildStandingsQuery"; diff --git a/apps/marketing/src/app/leaderboard/page.tsx b/apps/marketing/src/app/leaderboard/page.tsx new file mode 100644 index 00000000000..a895cd21eea --- /dev/null +++ b/apps/marketing/src/app/leaderboard/page.tsx @@ -0,0 +1,77 @@ +import { COMPANY } from "@superset/shared/constants"; +import type { Metadata } from "next"; +import { Silkscreen } from "next/font/google"; +import Link from "next/link"; +import { fetchStandings, fetchStats } from "@/app/utils/fetchLeaderboard"; +import { LeaderboardBoard } from "./components/LeaderboardBoard"; + +const pixel = Silkscreen({ + weight: ["400", "700"], + subsets: ["latin"], + display: "swap", +}); + +const TITLE = "Leaderboard"; +const DESCRIPTION = + "How much agent work engineers are actually running — tokens, cost, models and sessions, published by people who opted in."; + +export const metadata: Metadata = { + title: TITLE, + description: DESCRIPTION, + alternates: { canonical: "/leaderboard" }, + openGraph: { + title: `${TITLE} | ${COMPANY.NAME}`, + description: DESCRIPTION, + url: "/leaderboard", + images: ["/opengraph-image"], + }, + twitter: { + card: "summary_large_image", + title: `${TITLE} | ${COMPANY.NAME}`, + description: DESCRIPTION, + images: ["/opengraph-image"], + }, +}; + +export const revalidate = 300; + +const DEFAULT_PERIOD = "30d" as const; + +export default async function LeaderboardPage() { + const [standings, stats] = await Promise.all([ + fetchStandings({ period: DEFAULT_PERIOD, metric: "tokens", limit: 50 }), + fetchStats({ period: DEFAULT_PERIOD }), + ]); + + return ( +
+
+
+

+ Leaderboard +

+

+ Agent usage, ranked +

+ + See all stats → + +
+ +
+ +
+
+
+ ); +} diff --git a/apps/marketing/src/app/sitemap.ts b/apps/marketing/src/app/sitemap.ts index b67a53eaa6e..4537448b4d7 100644 --- a/apps/marketing/src/app/sitemap.ts +++ b/apps/marketing/src/app/sitemap.ts @@ -102,6 +102,18 @@ export default function sitemap(): MetadataRoute.Sitemap { changeFrequency: "monthly", priority: 0.8, }, + { + url: `${baseUrl}/leaderboard`, + lastModified: new Date(), + changeFrequency: "daily", + priority: 0.8, + }, + { + url: `${baseUrl}/stats`, + lastModified: new Date(), + changeFrequency: "daily", + priority: 0.7, + }, { url: `${baseUrl}/roadmap`, lastModified: new Date(), diff --git a/apps/marketing/src/app/starchart/components/DateRangePicker/DateRangePicker.tsx b/apps/marketing/src/app/starchart/components/DateRangePicker/DateRangePicker.tsx index 0e7f082f8ff..93eb754a7ad 100644 --- a/apps/marketing/src/app/starchart/components/DateRangePicker/DateRangePicker.tsx +++ b/apps/marketing/src/app/starchart/components/DateRangePicker/DateRangePicker.tsx @@ -5,6 +5,7 @@ import { Calendar } from "@superset/ui/calendar"; import { Popover, PopoverContent, PopoverTrigger } from "@superset/ui/popover"; import { CalendarIcon } from "lucide-react"; import type { DateRange } from "react-day-picker"; +import { formatRangeLabel } from "@/app/utils/formatRangeLabel"; interface DateRangePickerProps { range: DateRange | undefined; @@ -20,21 +21,6 @@ const PRESETS: Array<{ label: string; days: number | null }> = [ { label: "Last 6 months", days: 180 }, ]; -function formatDate(date: Date): string { - return date.toLocaleDateString("en-US", { - month: "short", - day: "numeric", - year: "numeric", - }); -} - -function formatRangeLabel(range: DateRange | undefined): string { - if (!range?.from) return "All time"; - return range.to - ? `${formatDate(range.from)} – ${formatDate(range.to)}` - : formatDate(range.from); -} - export function DateRangePicker({ range, onRangeChange, @@ -52,7 +38,7 @@ export function DateRangePicker({ diff --git a/apps/marketing/src/app/stats/components/StatsBody/StatsBody.tsx b/apps/marketing/src/app/stats/components/StatsBody/StatsBody.tsx new file mode 100644 index 00000000000..28d46daef39 --- /dev/null +++ b/apps/marketing/src/app/stats/components/StatsBody/StatsBody.tsx @@ -0,0 +1,73 @@ +import { + buildModelColors, + ModelBars, + toSpendRows, + toTokenRows, + toUserRows, +} from "@/app/components/ModelBars"; +import { StatStrip } from "@/app/components/StatStrip"; +import { TokenSplitBar } from "@/app/components/TokenSplitBar"; +import type { LeaderboardStats } from "@/app/utils/fetchLeaderboard"; +import { formatCount, formatTokens, formatUsd } from "@/app/utils/formatUsage"; +import { Panel } from "./components/Panel"; + +export function StatsBody({ + stats, + pixelClassName, +}: { + stats: LeaderboardStats; + pixelClassName: string; +}) { + const { totals, tokenSplit, models } = stats; + const colors = buildModelColors([ + models.byUsers, + models.bySpend, + models.byTokens, + ]); + const cacheShare = + totals.tokens > 0 + ? Math.round((tokenSplit.cachedInput / totals.tokens) * 100) + : 0; + + return ( +
+ + + + + + +
+ + + + + + + + + +
+
+ ); +} diff --git a/apps/marketing/src/app/stats/components/StatsBody/components/Panel/Panel.tsx b/apps/marketing/src/app/stats/components/StatsBody/components/Panel/Panel.tsx new file mode 100644 index 00000000000..ee8f467ed06 --- /dev/null +++ b/apps/marketing/src/app/stats/components/StatsBody/components/Panel/Panel.tsx @@ -0,0 +1,27 @@ +export function Panel({ + title, + meta, + children, + className, +}: { + title: string; + meta?: string; + children: React.ReactNode; + className?: string; +}) { + return ( +
+
+

+ {title} +

+ {meta && ( + + {meta} + + )} +
+ {children} +
+ ); +} diff --git a/apps/marketing/src/app/stats/components/StatsBody/components/Panel/index.ts b/apps/marketing/src/app/stats/components/StatsBody/components/Panel/index.ts new file mode 100644 index 00000000000..79bed340640 --- /dev/null +++ b/apps/marketing/src/app/stats/components/StatsBody/components/Panel/index.ts @@ -0,0 +1 @@ +export { Panel } from "./Panel"; diff --git a/apps/marketing/src/app/stats/components/StatsBody/index.ts b/apps/marketing/src/app/stats/components/StatsBody/index.ts new file mode 100644 index 00000000000..37280222fcf --- /dev/null +++ b/apps/marketing/src/app/stats/components/StatsBody/index.ts @@ -0,0 +1 @@ +export { StatsBody } from "./StatsBody"; diff --git a/apps/marketing/src/app/stats/components/Unavailable/Unavailable.tsx b/apps/marketing/src/app/stats/components/Unavailable/Unavailable.tsx new file mode 100644 index 00000000000..3e202fd6d54 --- /dev/null +++ b/apps/marketing/src/app/stats/components/Unavailable/Unavailable.tsx @@ -0,0 +1,9 @@ +export function Unavailable() { + return ( +
+

+ Stats are unavailable right now. +

+
+ ); +} diff --git a/apps/marketing/src/app/stats/components/Unavailable/index.ts b/apps/marketing/src/app/stats/components/Unavailable/index.ts new file mode 100644 index 00000000000..5bc5e154b37 --- /dev/null +++ b/apps/marketing/src/app/stats/components/Unavailable/index.ts @@ -0,0 +1 @@ +export { Unavailable } from "./Unavailable"; diff --git a/apps/marketing/src/app/stats/page.tsx b/apps/marketing/src/app/stats/page.tsx new file mode 100644 index 00000000000..5bc376f5c38 --- /dev/null +++ b/apps/marketing/src/app/stats/page.tsx @@ -0,0 +1,74 @@ +import { COMPANY } from "@superset/shared/constants"; +import type { Metadata } from "next"; +import { Silkscreen } from "next/font/google"; +import Link from "next/link"; +import { fetchStats } from "@/app/utils/fetchLeaderboard"; +import { formatDayRange } from "@/app/utils/formatUsage"; +import { StatsBody } from "./components/StatsBody"; +import { Unavailable } from "./components/Unavailable"; + +const pixel = Silkscreen({ + weight: ["400", "700"], + subsets: ["latin"], + display: "swap", +}); + +const TITLE = "Stats"; +const DESCRIPTION = + "Aggregate agent usage across every developer on the Superset leaderboard — tokens, cost, cache behaviour and which models people actually reach for."; + +export const metadata: Metadata = { + title: TITLE, + description: DESCRIPTION, + alternates: { canonical: "/stats" }, + openGraph: { + title: `${TITLE} | ${COMPANY.NAME}`, + description: DESCRIPTION, + url: "/stats", + images: ["/opengraph-image"], + }, + twitter: { + card: "summary_large_image", + title: `${TITLE} | ${COMPANY.NAME}`, + description: DESCRIPTION, + images: ["/opengraph-image"], + }, +}; + +export const revalidate = 3600; + +export default async function StatsPage() { + const stats = await fetchStats({ period: "all" }); + + return ( +
+
+
+

+ Stats +

+

+ Site-wide telemetry + {stats?.range ? ` · ${formatDayRange(stats.range)}` : " · all time"} +

+ + ← Back to leaderboard + +
+ +
+ {stats ? ( + + ) : ( + + )} +
+
+
+ ); +} diff --git a/apps/marketing/src/app/user/[handle]/assets/Inter-Bold.ttf b/apps/marketing/src/app/user/[handle]/assets/Inter-Bold.ttf new file mode 100644 index 00000000000..7cb7f4d145f Binary files /dev/null and b/apps/marketing/src/app/user/[handle]/assets/Inter-Bold.ttf differ diff --git a/apps/marketing/src/app/user/[handle]/components/OgStat/OgStat.tsx b/apps/marketing/src/app/user/[handle]/components/OgStat/OgStat.tsx new file mode 100644 index 00000000000..57148c52e1b --- /dev/null +++ b/apps/marketing/src/app/user/[handle]/components/OgStat/OgStat.tsx @@ -0,0 +1,14 @@ +import { OG_DIM } from "../../constants"; + +export function OgStat({ label, value }: { label: string; value: string }) { + return ( +
+
+ {value} +
+
+ {label.toUpperCase()} +
+
+ ); +} diff --git a/apps/marketing/src/app/user/[handle]/components/OgStat/index.ts b/apps/marketing/src/app/user/[handle]/components/OgStat/index.ts new file mode 100644 index 00000000000..bd846471957 --- /dev/null +++ b/apps/marketing/src/app/user/[handle]/components/OgStat/index.ts @@ -0,0 +1 @@ +export { OgStat } from "./OgStat"; diff --git a/apps/marketing/src/app/user/[handle]/components/ShareButtons/ShareButtons.tsx b/apps/marketing/src/app/user/[handle]/components/ShareButtons/ShareButtons.tsx new file mode 100644 index 00000000000..bf139585026 --- /dev/null +++ b/apps/marketing/src/app/user/[handle]/components/ShareButtons/ShareButtons.tsx @@ -0,0 +1,57 @@ +"use client"; + +import { CheckIcon, LinkIcon } from "lucide-react"; +import { useState } from "react"; +import { RiLinkedinBoxFill, RiTwitterXFill } from "react-icons/ri"; + +interface ShareButtonsProps { + url: string; + text: string; +} + +const BUTTON = + "inline-flex items-center gap-2 px-3 py-1.5 text-[0.68rem] font-mono uppercase tracking-[0.12em] border border-border rounded-[2px] text-muted-foreground hover:text-foreground hover:border-foreground/30 transition-colors"; + +export function ShareButtons({ url, text }: ShareButtonsProps) { + const [copied, setCopied] = useState(false); + + const copy = async () => { + try { + await navigator.clipboard.writeText(url); + setCopied(true); + + setTimeout(() => setCopied(false), 2000); + } catch {} + }; + + return ( +
+ + + Post + + + + Share + + +
+ ); +} diff --git a/apps/marketing/src/app/user/[handle]/components/ShareButtons/index.ts b/apps/marketing/src/app/user/[handle]/components/ShareButtons/index.ts new file mode 100644 index 00000000000..92d852c4526 --- /dev/null +++ b/apps/marketing/src/app/user/[handle]/components/ShareButtons/index.ts @@ -0,0 +1 @@ +export { ShareButtons } from "./ShareButtons"; diff --git a/apps/marketing/src/app/user/[handle]/constants.ts b/apps/marketing/src/app/user/[handle]/constants.ts new file mode 100644 index 00000000000..764ab7a8984 --- /dev/null +++ b/apps/marketing/src/app/user/[handle]/constants.ts @@ -0,0 +1,3 @@ +export const OG_BG = "#0a0a0a"; +export const OG_BRAND = "#d25611"; +export const OG_DIM = "#8b8b95"; diff --git a/apps/marketing/src/app/user/[handle]/opengraph-image.tsx b/apps/marketing/src/app/user/[handle]/opengraph-image.tsx new file mode 100644 index 00000000000..cbf2ffb87cd --- /dev/null +++ b/apps/marketing/src/app/user/[handle]/opengraph-image.tsx @@ -0,0 +1,88 @@ +import { COMPANY } from "@superset/shared/constants"; +import { ImageResponse } from "next/og"; +import { fetchParticipant } from "@/app/utils/fetchLeaderboard"; +import { formatTokens, formatUsd } from "@/app/utils/formatUsage"; +import { OgStat } from "./components/OgStat"; +import { OG_BG, OG_BRAND, OG_DIM } from "./constants"; +import { getInterBold } from "./utils/getInterBold"; + +export const alt = "Superset leaderboard profile"; +export const size = { width: 1200, height: 630 }; +export const contentType = "image/png"; + +const COMPANY_LABEL = `${COMPANY.NAME.toUpperCase()} LEADERBOARD`; + +export default async function Image({ + params, +}: { + params: Promise<{ handle: string }>; +}) { + const { handle } = await params; + const [profile, fontData] = await Promise.all([ + fetchParticipant(handle, { period: "all" }), + getInterBold(), + ]); + const fonts = [ + { + name: "Inter", + data: fontData, + weight: 700 as const, + style: "normal" as const, + }, + ]; + + if (!profile) { + return new ImageResponse( +
+ {COMPANY_LABEL} +
, + { ...size, fonts }, + ); + } + + const subtitle = `@${profile.handle} \u00b7 rank #${profile.rank} of ${profile.total}`; + + return new ImageResponse( +
+
+
+ {COMPANY_LABEL} +
+
+ {profile.name ?? `@${profile.handle}`} +
+
{subtitle}
+
+ +
+ + + +
+
, + { ...size, fonts }, + ); +} diff --git a/apps/marketing/src/app/user/[handle]/page.tsx b/apps/marketing/src/app/user/[handle]/page.tsx new file mode 100644 index 00000000000..4776e78298f --- /dev/null +++ b/apps/marketing/src/app/user/[handle]/page.tsx @@ -0,0 +1,186 @@ +import { COMPANY } from "@superset/shared/constants"; +import type { Metadata } from "next"; +import { Silkscreen } from "next/font/google"; +import Image from "next/image"; +import Link from "next/link"; +import { notFound } from "next/navigation"; +import { + buildModelColors, + ModelBars, + toTokenRows, +} from "@/app/components/ModelBars"; +import { StatStrip } from "@/app/components/StatStrip"; +import { TierTube } from "@/app/components/TierTube"; +import { TokenSplitBar } from "@/app/components/TokenSplitBar"; +import { avatarUrl } from "@/app/utils/avatarUrl"; +import { fetchParticipant } from "@/app/utils/fetchLeaderboard"; +import { + dayCount, + formatCount, + formatDayRange, + formatTokens, + formatUsd, +} from "@/app/utils/formatUsage"; +import { ShareButtons } from "./components/ShareButtons"; + +const pixel = Silkscreen({ + weight: ["400", "700"], + subsets: ["latin"], + display: "swap", +}); + +export const revalidate = 300; + +interface PageProps { + params: Promise<{ handle: string }>; +} + +export async function generateMetadata({ + params, +}: PageProps): Promise { + const { handle } = await params; + const profile = await fetchParticipant(handle, { period: "all" }); + + if (!profile) { + return { title: "Not found", robots: { index: false } }; + } + + const who = profile.name ?? `@${profile.handle}`; + const title = `${who} · #${profile.rank} on the ${COMPANY.NAME} leaderboard`; + const description = `${formatTokens(profile.allTime.tokens)} tokens and ${formatUsd( + profile.allTime.usd, + )} of API-equivalent agent usage across ${formatCount( + profile.models.length, + )} models.`; + const url = `/user/${profile.handle}`; + + return { + title, + description, + alternates: { canonical: url }, + + openGraph: { + title, + description, + url, + siteName: COMPANY.NAME, + type: "profile", + }, + twitter: { + card: "summary_large_image", + title, + description, + }, + }; +} + +export default async function UserProfilePage({ params }: PageProps) { + const { handle } = await params; + const profile = await fetchParticipant(handle, { period: "all" }); + + if (!profile) notFound(); + + const colors = buildModelColors([profile.models]); + const shareUrl = `${COMPANY.MARKETING_URL.replace(/\/$/, "")}/user/${profile.handle}`; + const shareText = `I'm #${profile.rank} on the ${COMPANY.NAME} leaderboard with ${formatTokens( + profile.allTime.tokens, + )} tokens of agent usage.`; + + return ( +
+
+ + ← Back to leaderboard + + +
+ +

+ {profile.name ?? profile.handle} +

+

+ @{profile.handle} · rank #{profile.rank} of {profile.total} +

+ +
+ +
+
+ +
+ + + + +
+

+ Models +

+ ({ ...model, usd: model.usd })), + )} + colors={colors} + /> +
+ +
+

+ Token breakdown +

+ +
+
+
+
+ ); +} diff --git a/apps/marketing/src/app/user/[handle]/utils/getInterBold/getInterBold.ts b/apps/marketing/src/app/user/[handle]/utils/getInterBold/getInterBold.ts new file mode 100644 index 00000000000..99b695ffb9e --- /dev/null +++ b/apps/marketing/src/app/user/[handle]/utils/getInterBold/getInterBold.ts @@ -0,0 +1,10 @@ +let interBoldPromise: Promise | null = null; + +export function getInterBold(): Promise { + if (!interBoldPromise) { + interBoldPromise = fetch( + new URL("../../assets/Inter-Bold.ttf", import.meta.url), + ).then((res) => res.arrayBuffer()); + } + return interBoldPromise; +} diff --git a/apps/marketing/src/app/user/[handle]/utils/getInterBold/index.ts b/apps/marketing/src/app/user/[handle]/utils/getInterBold/index.ts new file mode 100644 index 00000000000..09273449cbb --- /dev/null +++ b/apps/marketing/src/app/user/[handle]/utils/getInterBold/index.ts @@ -0,0 +1 @@ +export { getInterBold } from "./getInterBold"; diff --git a/apps/marketing/src/app/utils/avatarUrl/avatarUrl.ts b/apps/marketing/src/app/utils/avatarUrl/avatarUrl.ts new file mode 100644 index 00000000000..817e09329c3 --- /dev/null +++ b/apps/marketing/src/app/utils/avatarUrl/avatarUrl.ts @@ -0,0 +1,12 @@ +const STYLE = "voxel-bot"; + +const PARAMS = [ + "chestVariant=vents,screen,heart,dial,slot", + "backgroundColor=ddd8cd", + "bodyColor=a8a396,8c9b8f,9a8f80,8896a3,a0919b,b0a58c", + "glowColor=c8b98f,9fb0a6,b09a9a", +].join("&"); + +export function avatarUrl(handle: string): string { + return `https://api.dicebear.com/10.x/${STYLE}/svg?${PARAMS}&seed=${encodeURIComponent(handle)}`; +} diff --git a/apps/marketing/src/app/utils/avatarUrl/index.ts b/apps/marketing/src/app/utils/avatarUrl/index.ts new file mode 100644 index 00000000000..0bb6cf564be --- /dev/null +++ b/apps/marketing/src/app/utils/avatarUrl/index.ts @@ -0,0 +1 @@ +export { avatarUrl } from "./avatarUrl"; diff --git a/apps/marketing/src/app/utils/fetchLeaderboard/fetchLeaderboard.ts b/apps/marketing/src/app/utils/fetchLeaderboard/fetchLeaderboard.ts new file mode 100644 index 00000000000..fac44813f11 --- /dev/null +++ b/apps/marketing/src/app/utils/fetchLeaderboard/fetchLeaderboard.ts @@ -0,0 +1,75 @@ +import type { RouterOutputs } from "@superset/trpc"; +import type { LeaderboardPeriod } from "@superset/trpc/leaderboard-periods"; +import type { LeaderboardMetric } from "@superset/trpc/leaderboard-types"; +import { TRPCClientError } from "@trpc/client"; +import { leaderboardClient } from "../leaderboardClient"; + +export type { LeaderboardMetric, LeaderboardPeriod }; + +type PublicLeaderboard = RouterOutputs["leaderboard"]["public"]; + +export type Standings = PublicLeaderboard["standings"]; +export type StandingRow = Standings["rows"][number]; +export type LeaderboardStats = PublicLeaderboard["stats"]; +export type ParticipantProfile = PublicLeaderboard["participant"]; + +export interface RangeQuery { + period?: LeaderboardPeriod; + from?: string; + to?: string; +} + +export interface StandingsQuery extends RangeQuery { + metric?: LeaderboardMetric; + limit?: number; + offset?: number; +} + +export async function fetchStandings( + options: StandingsQuery = {}, + signal?: AbortSignal, +): Promise { + try { + return await leaderboardClient.leaderboard.public.standings.query(options, { + signal, + }); + } catch (error) { + console.error("[marketing/leaderboard] standings error:", error); + return null; + } +} + +export async function fetchStats( + options: RangeQuery = {}, + signal?: AbortSignal, +): Promise { + try { + return await leaderboardClient.leaderboard.public.stats.query(options, { + signal, + }); + } catch (error) { + console.error("[marketing/leaderboard] stats error:", error); + return null; + } +} + +/** + * Only a real NOT_FOUND means the profile is missing. Transient failures throw + * so ISR keeps serving the stale page instead of caching a 404 for a live one. + */ +export async function fetchParticipant( + handle: string, + options: RangeQuery = {}, +): Promise { + try { + return await leaderboardClient.leaderboard.public.participant.query({ + handle, + ...options, + }); + } catch (error) { + if (error instanceof TRPCClientError && error.data?.code === "NOT_FOUND") { + return null; + } + throw error; + } +} diff --git a/apps/marketing/src/app/utils/fetchLeaderboard/index.ts b/apps/marketing/src/app/utils/fetchLeaderboard/index.ts new file mode 100644 index 00000000000..7b56e6b7fed --- /dev/null +++ b/apps/marketing/src/app/utils/fetchLeaderboard/index.ts @@ -0,0 +1,15 @@ +export type { + LeaderboardMetric, + LeaderboardPeriod, + LeaderboardStats, + ParticipantProfile, + RangeQuery, + StandingRow, + Standings, + StandingsQuery, +} from "./fetchLeaderboard"; +export { + fetchParticipant, + fetchStandings, + fetchStats, +} from "./fetchLeaderboard"; diff --git a/apps/marketing/src/app/utils/formatRangeLabel/formatRangeLabel.ts b/apps/marketing/src/app/utils/formatRangeLabel/formatRangeLabel.ts new file mode 100644 index 00000000000..4fc1a7d709e --- /dev/null +++ b/apps/marketing/src/app/utils/formatRangeLabel/formatRangeLabel.ts @@ -0,0 +1,14 @@ +import { format } from "date-fns"; +import type { DateRange } from "react-day-picker"; + +export function formatRangeLabel( + range: DateRange | undefined, + fallback: string, + pattern = "MMM d", +): string { + if (!range?.from) return fallback; + const label = (date: Date) => format(date, pattern); + return range.to + ? `${label(range.from)} – ${label(range.to)}` + : label(range.from); +} diff --git a/apps/marketing/src/app/utils/formatRangeLabel/index.ts b/apps/marketing/src/app/utils/formatRangeLabel/index.ts new file mode 100644 index 00000000000..15140583708 --- /dev/null +++ b/apps/marketing/src/app/utils/formatRangeLabel/index.ts @@ -0,0 +1 @@ +export { formatRangeLabel } from "./formatRangeLabel"; diff --git a/apps/marketing/src/app/utils/formatUsage/formatUsage.test.ts b/apps/marketing/src/app/utils/formatUsage/formatUsage.test.ts new file mode 100644 index 00000000000..df6b50662e2 --- /dev/null +++ b/apps/marketing/src/app/utils/formatUsage/formatUsage.test.ts @@ -0,0 +1,72 @@ +import { describe, expect, it } from "bun:test"; +import { + dayCount, + formatCount, + formatDayRange, + formatUsd, +} from "./formatUsage"; + +describe("formatUsd", () => { + it("scales through K/M", () => { + expect(formatUsd(1_240_000)).toBe("$1.24M"); + expect(formatUsd(4_200)).toBe("$4.2K"); + expect(formatUsd(46.204)).toBe("$46.20"); + }); + + it("promotes values that round up into the next unit", () => { + expect(formatUsd(999_999)).toBe("$1.00M"); + expect(formatUsd(999_990)).toBe("$1.00M"); + }); + + it("keeps values that stay inside their unit", () => { + expect(formatUsd(1_000)).toBe("$1.0K"); + expect(formatUsd(999_400)).toBe("$999.4K"); + expect(formatUsd(1_000_000)).toBe("$1.00M"); + }); + + it("accepts numeric strings and rejects junk", () => { + expect(formatUsd("1240000")).toBe("$1.24M"); + expect(formatUsd("not a number")).toBe("$0"); + }); +}); + +describe("formatCount", () => { + it("scales through K/M", () => { + expect(formatCount(4_200_000)).toBe("4.2M"); + expect(formatCount(4_200)).toBe("4.2K"); + expect(formatCount(312)).toBe("312"); + }); + + it("promotes values that round up into the next unit", () => { + expect(formatCount(999_999)).toBe("1.0M"); + }); + + it("keeps values that stay inside their unit", () => { + expect(formatCount(1_000)).toBe("1.0K"); + expect(formatCount(999_400)).toBe("999.4K"); + expect(formatCount(1_000_000)).toBe("1.0M"); + }); +}); + +describe("formatDayRange", () => { + it("renders the calendar days of the key, not a shifted local day", () => { + expect(formatDayRange({ from: "2026-08-01", to: "2026-08-25" })).toBe( + "Aug 1 – Aug 25", + ); + }); + + it("falls back to all time without a range", () => { + expect(formatDayRange(null)).toBe("All time"); + }); +}); + +describe("dayCount", () => { + it("counts both endpoints", () => { + expect(dayCount({ from: "2026-08-01", to: "2026-08-25" })).toBe(25); + expect(dayCount({ from: "2026-08-25", to: "2026-08-25" })).toBe(1); + }); + + it("is zero without a range", () => { + expect(dayCount(null)).toBe(0); + }); +}); diff --git a/apps/marketing/src/app/utils/formatUsage/formatUsage.ts b/apps/marketing/src/app/utils/formatUsage/formatUsage.ts new file mode 100644 index 00000000000..243153b970a --- /dev/null +++ b/apps/marketing/src/app/utils/formatUsage/formatUsage.ts @@ -0,0 +1,34 @@ +import { formatScaled, type ScaleUnit } from "@superset/shared/format-scaled"; +import { differenceInCalendarDays, format, parseISO } from "date-fns"; + +export { formatTokens } from "@superset/shared/format-tokens"; + +const USD_UNITS: readonly ScaleUnit[] = [ + { limit: 1e6, suffix: "M", digits: 2 }, + { limit: 1e3, suffix: "K", digits: 1 }, +]; + +const COUNT_UNITS: readonly ScaleUnit[] = [ + { limit: 1e6, suffix: "M", digits: 1 }, + { limit: 1e3, suffix: "K", digits: 1 }, +]; + +export function formatUsd(usd: string | number): string { + const value = typeof usd === "string" ? Number.parseFloat(usd) : usd; + if (!Number.isFinite(value)) return "$0"; + return `$${formatScaled(value, USD_UNITS, (raw) => raw.toFixed(2))}`; +} + +export function formatCount(value: number): string { + return formatScaled(value, COUNT_UNITS, (raw) => raw.toLocaleString("en-US")); +} + +export function formatDayRange(range: { from: string; to: string } | null) { + if (!range) return "All time"; + return `${format(parseISO(range.from), "MMM d")} – ${format(parseISO(range.to), "MMM d")}`; +} + +export function dayCount(range: { from: string; to: string } | null): number { + if (!range) return 0; + return differenceInCalendarDays(parseISO(range.to), parseISO(range.from)) + 1; +} diff --git a/apps/marketing/src/app/utils/formatUsage/index.ts b/apps/marketing/src/app/utils/formatUsage/index.ts new file mode 100644 index 00000000000..932e73d5649 --- /dev/null +++ b/apps/marketing/src/app/utils/formatUsage/index.ts @@ -0,0 +1,7 @@ +export { + dayCount, + formatCount, + formatDayRange, + formatTokens, + formatUsd, +} from "./formatUsage"; diff --git a/apps/marketing/src/app/utils/leaderboardClient/index.ts b/apps/marketing/src/app/utils/leaderboardClient/index.ts new file mode 100644 index 00000000000..674cbc85122 --- /dev/null +++ b/apps/marketing/src/app/utils/leaderboardClient/index.ts @@ -0,0 +1 @@ +export * from "./leaderboardClient"; diff --git a/apps/marketing/src/app/utils/leaderboardClient/leaderboardClient.ts b/apps/marketing/src/app/utils/leaderboardClient/leaderboardClient.ts new file mode 100644 index 00000000000..ccb6be959ba --- /dev/null +++ b/apps/marketing/src/app/utils/leaderboardClient/leaderboardClient.ts @@ -0,0 +1,22 @@ +import type { AppRouter } from "@superset/trpc"; +import { createTRPCClient, httpBatchLink } from "@trpc/client"; +import superjson from "superjson"; +import { env } from "@/env"; + +export const REVALIDATE_SECONDS = 300; + +/** + * Anonymous reader for `leaderboard.public.*`. tRPC sends queries as GET, so the + * URLs stay stable and cacheable by the CDN; the `next` option makes the ISR + * pages revalidate on the same window and is ignored in the browser. + */ +export const leaderboardClient = createTRPCClient({ + links: [ + httpBatchLink({ + url: `${env.NEXT_PUBLIC_API_URL}/api/trpc`, + transformer: superjson, + fetch: (url, options) => + fetch(url, { ...options, next: { revalidate: REVALIDATE_SECONDS } }), + }), + ], +}); diff --git a/apps/marketing/tsconfig.json b/apps/marketing/tsconfig.json index d658715228f..412cbc12c3c 100644 --- a/apps/marketing/tsconfig.json +++ b/apps/marketing/tsconfig.json @@ -1,6 +1,7 @@ { "extends": "@superset/typescript/next.json", "compilerOptions": { + "types": ["bun-types"], "paths": { "@/*": ["./src/*"] } diff --git a/bun.lock b/bun.lock index b8188662b1e..9dfc406d425 100644 --- a/bun.lock +++ b/bun.lock @@ -426,10 +426,13 @@ "@superset/auth": "workspace:*", "@superset/email": "workspace:*", "@superset/shared": "workspace:*", + "@superset/trpc": "workspace:*", "@superset/ui": "workspace:*", "@t3-oss/env-nextjs": "0.13.11", + "@trpc/client": "11.16.0", "@upstash/ratelimit": "2.0.8", "@upstash/redis": "1.37.0", + "date-fns": "4.1.0", "framer-motion": "12.38.0", "geist": "1.7.0", "gray-matter": "4.0.3", @@ -452,6 +455,7 @@ "shiki": "3.23.0", "simplex-noise": "4.0.3", "stripe-gradient": "1.0.1", + "superjson": "2.2.6", "three": "0.181.2", "zod": "4.4.3", }, @@ -465,6 +469,7 @@ "@types/react-dom": "19.2.3", "@types/three": "0.181.0", "babel-plugin-react-compiler": "1.0.0", + "bun-types": "1.3.14", "dotenv": "17.3.1", "tailwindcss": "4.2.2", "typescript": "6.0.3", diff --git a/packages/db/drizzle/0094_add_leaderboard_and_tier_tables.sql b/packages/db/drizzle/0094_add_leaderboard_and_tier_tables.sql new file mode 100644 index 00000000000..2427fd7d7e9 --- /dev/null +++ b/packages/db/drizzle/0094_add_leaderboard_and_tier_tables.sql @@ -0,0 +1,82 @@ +CREATE TYPE "public"."leaderboard_visibility" AS ENUM('public', 'hidden');--> statement-breakpoint +CREATE TABLE "leaderboard_daily" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "user_id" uuid NOT NULL, + "day" date NOT NULL, + "provider" text NOT NULL, + "model" text NOT NULL, + "host_id" text NOT NULL, + "uncached_input" bigint DEFAULT 0 NOT NULL, + "cached_input" bigint DEFAULT 0 NOT NULL, + "cache_write_5m" bigint DEFAULT 0 NOT NULL, + "cache_write_1h" bigint DEFAULT 0 NOT NULL, + "output" bigint DEFAULT 0 NOT NULL, + "reasoning_output" bigint DEFAULT 0 NOT NULL, + "tokens" bigint DEFAULT 0 NOT NULL, + "usd_estimate" numeric(14, 6) DEFAULT '0' NOT NULL, + "approximate" boolean DEFAULT false NOT NULL, + "sessions" integer DEFAULT 0 NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "updated_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "leaderboard_daily_identity_key" UNIQUE("user_id","day","provider","model","host_id") +); +--> statement-breakpoint +CREATE TABLE "leaderboard_daily_factory" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "user_id" uuid NOT NULL, + "day" date NOT NULL, + "host_id" text NOT NULL, + "sessions" integer DEFAULT 0 NOT NULL, + "parallel_sessions" numeric(6, 2) DEFAULT '0' NOT NULL, + "agent_prs_merged" integer DEFAULT 0 NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "updated_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "leaderboard_daily_factory_identity_key" UNIQUE("user_id","day","host_id") +); +--> statement-breakpoint +CREATE TABLE "leaderboard_participants" ( + "user_id" uuid PRIMARY KEY NOT NULL, + "handle" text NOT NULL, + "visibility" "leaderboard_visibility" DEFAULT 'public' NOT NULL, + "organization_id" uuid, + "opted_in_at" timestamp with time zone DEFAULT now() NOT NULL, + "revoked_at" timestamp with time zone, + "flagged_at" timestamp with time zone, + "last_published_at" timestamp with time zone, + "payload_version" integer DEFAULT 1 NOT NULL, + "tokens" bigint DEFAULT 0 NOT NULL, + "usd" numeric(20, 6) DEFAULT '0' NOT NULL, + "sessions" integer DEFAULT 0 NOT NULL, + "uncached_input" bigint DEFAULT 0 NOT NULL, + "cached_input" bigint DEFAULT 0 NOT NULL, + "cache_write_5m" bigint DEFAULT 0 NOT NULL, + "cache_write_1h" bigint DEFAULT 0 NOT NULL, + "output" bigint DEFAULT 0 NOT NULL, + "reasoning_output" bigint DEFAULT 0 NOT NULL, + "approximate" boolean DEFAULT false NOT NULL, + "day_range_start" date, + "day_range_end" date, + "tier" integer DEFAULT 0 NOT NULL, + "tier_computed_at" timestamp with time zone, + "active_days" integer DEFAULT 0 NOT NULL, + "axis_width" numeric(6, 2) DEFAULT '0' NOT NULL, + "axis_depth" bigint DEFAULT 0 NOT NULL, + "axis_output" numeric(8, 2) DEFAULT '0' NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "updated_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "leaderboard_participants_handle_unique" UNIQUE("handle") +); +--> statement-breakpoint +ALTER TABLE "leaderboard_daily" ADD CONSTRAINT "leaderboard_daily_user_id_leaderboard_participants_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."leaderboard_participants"("user_id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "leaderboard_daily_factory" ADD CONSTRAINT "leaderboard_daily_factory_user_id_leaderboard_participants_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."leaderboard_participants"("user_id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "leaderboard_participants" ADD CONSTRAINT "leaderboard_participants_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "auth"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "leaderboard_participants" ADD CONSTRAINT "leaderboard_participants_organization_id_organizations_id_fk" FOREIGN KEY ("organization_id") REFERENCES "auth"."organizations"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint +CREATE INDEX "leaderboard_daily_day_idx" ON "leaderboard_daily" USING btree ("day");--> statement-breakpoint +CREATE INDEX "leaderboard_daily_user_day_idx" ON "leaderboard_daily" USING btree ("user_id","day");--> statement-breakpoint +CREATE INDEX "leaderboard_daily_model_day_idx" ON "leaderboard_daily" USING btree ("model","day");--> statement-breakpoint +CREATE INDEX "leaderboard_daily_factory_day_idx" ON "leaderboard_daily_factory" USING btree ("day");--> statement-breakpoint +CREATE INDEX "leaderboard_daily_factory_user_day_idx" ON "leaderboard_daily_factory" USING btree ("user_id","day");--> statement-breakpoint +CREATE INDEX "leaderboard_participants_tokens_idx" ON "leaderboard_participants" USING btree ("tokens");--> statement-breakpoint +CREATE INDEX "leaderboard_participants_org_idx" ON "leaderboard_participants" USING btree ("organization_id");--> statement-breakpoint +CREATE INDEX "leaderboard_participants_usd_idx" ON "leaderboard_participants" USING btree ("usd");--> statement-breakpoint +CREATE INDEX "leaderboard_participants_tier_idx" ON "leaderboard_participants" USING btree ("tier"); \ No newline at end of file diff --git a/packages/db/drizzle/meta/0094_snapshot.json b/packages/db/drizzle/meta/0094_snapshot.json new file mode 100644 index 00000000000..fa4faadfaba --- /dev/null +++ b/packages/db/drizzle/meta/0094_snapshot.json @@ -0,0 +1,8604 @@ +{ + "id": "da182aae-eef3-47bf-9019-ca972cf72723", + "prevId": "53cafbab-ae82-4391-98df-66ebc6a43d8b", + "version": "7", + "dialect": "postgresql", + "tables": { + "auth.accounts": { + "name": "accounts", + "schema": "auth", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "account_id": { + "name": "account_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "access_token": { + "name": "access_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "refresh_token": { + "name": "refresh_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "id_token": { + "name": "id_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "access_token_expires_at": { + "name": "access_token_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "refresh_token_expires_at": { + "name": "refresh_token_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "password": { + "name": "password", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "accounts_user_id_idx": { + "name": "accounts_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "accounts_user_id_users_id_fk": { + "name": "accounts_user_id_users_id_fk", + "tableFrom": "accounts", + "tableTo": "users", + "schemaTo": "auth", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "auth.apikeys": { + "name": "apikeys", + "schema": "auth", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "config_id": { + "name": "config_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'default'" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "start": { + "name": "start", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reference_id": { + "name": "reference_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "prefix": { + "name": "prefix", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "refill_interval": { + "name": "refill_interval", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "refill_amount": { + "name": "refill_amount", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "last_refill_at": { + "name": "last_refill_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": true + }, + "rate_limit_enabled": { + "name": "rate_limit_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": true + }, + "rate_limit_time_window": { + "name": "rate_limit_time_window", + "type": "integer", + "primaryKey": false, + "notNull": false, + "default": 86400000 + }, + "rate_limit_max": { + "name": "rate_limit_max", + "type": "integer", + "primaryKey": false, + "notNull": false, + "default": 10 + }, + "request_count": { + "name": "request_count", + "type": "integer", + "primaryKey": false, + "notNull": false, + "default": 0 + }, + "remaining": { + "name": "remaining", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "last_request": { + "name": "last_request", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "permissions": { + "name": "permissions", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "metadata": { + "name": "metadata", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false, + "generated": { + "as": "CASE\n\t\t\t\tWHEN metadata IS NULL OR metadata = '' THEN NULL\n\t\t\t\tWHEN NOT (metadata IS JSON OBJECT) THEN NULL\n\t\t\t\tWHEN (metadata::jsonb->>'organizationId') ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'\n\t\t\t\t\tTHEN (metadata::jsonb->>'organizationId')::uuid\n\t\t\t\tELSE NULL\n\t\t\tEND", + "type": "stored" + } + } + }, + "indexes": { + "apikeys_configId_idx": { + "name": "apikeys_configId_idx", + "columns": [ + { + "expression": "config_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "apikeys_referenceId_idx": { + "name": "apikeys_referenceId_idx", + "columns": [ + { + "expression": "reference_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "apikeys_key_idx": { + "name": "apikeys_key_idx", + "columns": [ + { + "expression": "key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "apikeys_organization_id_idx": { + "name": "apikeys_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "apikeys_metadata_trgm_idx": { + "name": "apikeys_metadata_trgm_idx", + "columns": [ + { + "expression": "\"metadata\" gin_trgm_ops", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "gin", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "auth.device_codes": { + "name": "device_codes", + "schema": "auth", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "device_code": { + "name": "device_code", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_code": { + "name": "user_code", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "last_polled_at": { + "name": "last_polled_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "polling_interval": { + "name": "polling_interval", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "auth.invitations": { + "name": "invitations", + "schema": "auth", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "inviter_id": { + "name": "inviter_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "team_id": { + "name": "team_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "invitations_organization_id_idx": { + "name": "invitations_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "invitations_email_idx": { + "name": "invitations_email_idx", + "columns": [ + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "invitations_organization_id_organizations_id_fk": { + "name": "invitations_organization_id_organizations_id_fk", + "tableFrom": "invitations", + "tableTo": "organizations", + "schemaTo": "auth", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "invitations_inviter_id_users_id_fk": { + "name": "invitations_inviter_id_users_id_fk", + "tableFrom": "invitations", + "tableTo": "users", + "schemaTo": "auth", + "columnsFrom": [ + "inviter_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "invitations_team_id_teams_id_fk": { + "name": "invitations_team_id_teams_id_fk", + "tableFrom": "invitations", + "tableTo": "teams", + "schemaTo": "auth", + "columnsFrom": [ + "team_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "auth.jwkss": { + "name": "jwkss", + "schema": "auth", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "public_key": { + "name": "public_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "private_key": { + "name": "private_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "auth.members": { + "name": "members", + "schema": "auth", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'member'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "members_organization_id_idx": { + "name": "members_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "members_user_id_idx": { + "name": "members_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "members_organization_id_organizations_id_fk": { + "name": "members_organization_id_organizations_id_fk", + "tableFrom": "members", + "tableTo": "organizations", + "schemaTo": "auth", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "members_user_id_users_id_fk": { + "name": "members_user_id_users_id_fk", + "tableFrom": "members", + "tableTo": "users", + "schemaTo": "auth", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "auth.oauth_access_tokens": { + "name": "oauth_access_tokens", + "schema": "auth", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "session_id": { + "name": "session_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "reference_id": { + "name": "reference_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "refresh_id": { + "name": "refresh_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "scopes": { + "name": "scopes", + "type": "text[]", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "oauth_access_tokens_client_id_oauth_clients_client_id_fk": { + "name": "oauth_access_tokens_client_id_oauth_clients_client_id_fk", + "tableFrom": "oauth_access_tokens", + "tableTo": "oauth_clients", + "schemaTo": "auth", + "columnsFrom": [ + "client_id" + ], + "columnsTo": [ + "client_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_access_tokens_session_id_sessions_id_fk": { + "name": "oauth_access_tokens_session_id_sessions_id_fk", + "tableFrom": "oauth_access_tokens", + "tableTo": "sessions", + "schemaTo": "auth", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "oauth_access_tokens_user_id_users_id_fk": { + "name": "oauth_access_tokens_user_id_users_id_fk", + "tableFrom": "oauth_access_tokens", + "tableTo": "users", + "schemaTo": "auth", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_access_tokens_refresh_id_oauth_refresh_tokens_id_fk": { + "name": "oauth_access_tokens_refresh_id_oauth_refresh_tokens_id_fk", + "tableFrom": "oauth_access_tokens", + "tableTo": "oauth_refresh_tokens", + "schemaTo": "auth", + "columnsFrom": [ + "refresh_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "oauth_access_tokens_token_unique": { + "name": "oauth_access_tokens_token_unique", + "nullsNotDistinct": false, + "columns": [ + "token" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "auth.oauth_clients": { + "name": "oauth_clients", + "schema": "auth", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "client_secret": { + "name": "client_secret", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "disabled": { + "name": "disabled", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": false + }, + "skip_consent": { + "name": "skip_consent", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "enable_end_session": { + "name": "enable_end_session", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "scopes": { + "name": "scopes", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "uri": { + "name": "uri", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "icon": { + "name": "icon", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "contacts": { + "name": "contacts", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "tos": { + "name": "tos", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "policy": { + "name": "policy", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "software_id": { + "name": "software_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "software_version": { + "name": "software_version", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "software_statement": { + "name": "software_statement", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "redirect_uris": { + "name": "redirect_uris", + "type": "text[]", + "primaryKey": false, + "notNull": true + }, + "post_logout_redirect_uris": { + "name": "post_logout_redirect_uris", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "token_endpoint_auth_method": { + "name": "token_endpoint_auth_method", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "grant_types": { + "name": "grant_types", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "response_types": { + "name": "response_types", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "public": { + "name": "public", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "require_pkce": { + "name": "require_pkce", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "subject_type": { + "name": "subject_type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reference_id": { + "name": "reference_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "oauth_clients_user_id_users_id_fk": { + "name": "oauth_clients_user_id_users_id_fk", + "tableFrom": "oauth_clients", + "tableTo": "users", + "schemaTo": "auth", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "oauth_clients_client_id_unique": { + "name": "oauth_clients_client_id_unique", + "nullsNotDistinct": false, + "columns": [ + "client_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "auth.oauth_consents": { + "name": "oauth_consents", + "schema": "auth", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "reference_id": { + "name": "reference_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "scopes": { + "name": "scopes", + "type": "text[]", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "oauth_consents_client_id_oauth_clients_client_id_fk": { + "name": "oauth_consents_client_id_oauth_clients_client_id_fk", + "tableFrom": "oauth_consents", + "tableTo": "oauth_clients", + "schemaTo": "auth", + "columnsFrom": [ + "client_id" + ], + "columnsTo": [ + "client_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_consents_user_id_users_id_fk": { + "name": "oauth_consents_user_id_users_id_fk", + "tableFrom": "oauth_consents", + "tableTo": "users", + "schemaTo": "auth", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "auth.oauth_refresh_tokens": { + "name": "oauth_refresh_tokens", + "schema": "auth", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "session_id": { + "name": "session_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "reference_id": { + "name": "reference_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "revoked": { + "name": "revoked", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "auth_time": { + "name": "auth_time", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "scopes": { + "name": "scopes", + "type": "text[]", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "oauth_refresh_tokens_client_id_oauth_clients_client_id_fk": { + "name": "oauth_refresh_tokens_client_id_oauth_clients_client_id_fk", + "tableFrom": "oauth_refresh_tokens", + "tableTo": "oauth_clients", + "schemaTo": "auth", + "columnsFrom": [ + "client_id" + ], + "columnsTo": [ + "client_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_refresh_tokens_session_id_sessions_id_fk": { + "name": "oauth_refresh_tokens_session_id_sessions_id_fk", + "tableFrom": "oauth_refresh_tokens", + "tableTo": "sessions", + "schemaTo": "auth", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "oauth_refresh_tokens_user_id_users_id_fk": { + "name": "oauth_refresh_tokens_user_id_users_id_fk", + "tableFrom": "oauth_refresh_tokens", + "tableTo": "users", + "schemaTo": "auth", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "auth.organizations": { + "name": "organizations", + "schema": "auth", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "logo": { + "name": "logo", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "metadata": { + "name": "metadata", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "stripe_customer_id": { + "name": "stripe_customer_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "allowed_domains": { + "name": "allowed_domains", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + } + }, + "indexes": { + "organizations_slug_idx": { + "name": "organizations_slug_idx", + "columns": [ + { + "expression": "slug", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "organizations_allowed_domains_idx": { + "name": "organizations_allowed_domains_idx", + "columns": [ + { + "expression": "allowed_domains", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "gin", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "organizations_slug_unique": { + "name": "organizations_slug_unique", + "nullsNotDistinct": false, + "columns": [ + "slug" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "auth.sessions": { + "name": "sessions", + "schema": "auth", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "ip_address": { + "name": "ip_address", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_agent": { + "name": "user_agent", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "active_organization_id": { + "name": "active_organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "active_team_id": { + "name": "active_team_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "sessions_user_id_idx": { + "name": "sessions_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "sessions_user_id_users_id_fk": { + "name": "sessions_user_id_users_id_fk", + "tableFrom": "sessions", + "tableTo": "users", + "schemaTo": "auth", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "sessions_token_unique": { + "name": "sessions_token_unique", + "nullsNotDistinct": false, + "columns": [ + "token" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "auth.team_members": { + "name": "team_members", + "schema": "auth", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "team_id": { + "name": "team_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + } + }, + "indexes": { + "team_members_team_id_idx": { + "name": "team_members_team_id_idx", + "columns": [ + { + "expression": "team_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "team_members_user_id_idx": { + "name": "team_members_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "team_members_organization_id_idx": { + "name": "team_members_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "team_members_team_user_unique": { + "name": "team_members_team_user_unique", + "columns": [ + { + "expression": "team_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "team_members_team_id_teams_id_fk": { + "name": "team_members_team_id_teams_id_fk", + "tableFrom": "team_members", + "tableTo": "teams", + "schemaTo": "auth", + "columnsFrom": [ + "team_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "team_members_user_id_users_id_fk": { + "name": "team_members_user_id_users_id_fk", + "tableFrom": "team_members", + "tableTo": "users", + "schemaTo": "auth", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "team_members_organization_id_organizations_id_fk": { + "name": "team_members_organization_id_organizations_id_fk", + "tableFrom": "team_members", + "tableTo": "organizations", + "schemaTo": "auth", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "auth.teams": { + "name": "teams", + "schema": "auth", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + } + }, + "indexes": { + "teams_organization_id_idx": { + "name": "teams_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "teams_org_slug_unique": { + "name": "teams_org_slug_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "slug", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "teams_organization_id_organizations_id_fk": { + "name": "teams_organization_id_organizations_id_fk", + "tableFrom": "teams", + "tableTo": "organizations", + "schemaTo": "auth", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "auth.users": { + "name": "users", + "schema": "auth", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email_verified": { + "name": "email_verified", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_ids": { + "name": "organization_ids", + "type": "uuid[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "onboarded_at": { + "name": "onboarded_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "deletion_requested_at": { + "name": "deletion_requested_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "users_organization_ids_idx": { + "name": "users_organization_ids_idx", + "columns": [ + { + "expression": "organization_ids", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "gin", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "users_email_unique": { + "name": "users_email_unique", + "nullsNotDistinct": false, + "columns": [ + "email" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "auth.verifications": { + "name": "verifications", + "schema": "auth", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "identifier": { + "name": "identifier", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "verifications_identifier_idx": { + "name": "verifications_identifier_idx", + "columns": [ + { + "expression": "identifier", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.github_installations": { + "name": "github_installations", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "connected_by_user_id": { + "name": "connected_by_user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "installation_id": { + "name": "installation_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "account_login": { + "name": "account_login", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "account_type": { + "name": "account_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "permissions": { + "name": "permissions", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "suspended": { + "name": "suspended", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "suspended_at": { + "name": "suspended_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_synced_at": { + "name": "last_synced_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "github_installations_installation_id_idx": { + "name": "github_installations_installation_id_idx", + "columns": [ + { + "expression": "installation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "github_installations_organization_id_organizations_id_fk": { + "name": "github_installations_organization_id_organizations_id_fk", + "tableFrom": "github_installations", + "tableTo": "organizations", + "schemaTo": "auth", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "github_installations_connected_by_user_id_users_id_fk": { + "name": "github_installations_connected_by_user_id_users_id_fk", + "tableFrom": "github_installations", + "tableTo": "users", + "schemaTo": "auth", + "columnsFrom": [ + "connected_by_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "github_installations_installation_id_unique": { + "name": "github_installations_installation_id_unique", + "nullsNotDistinct": false, + "columns": [ + "installation_id" + ] + }, + "github_installations_org_unique": { + "name": "github_installations_org_unique", + "nullsNotDistinct": false, + "columns": [ + "organization_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.github_pull_requests": { + "name": "github_pull_requests", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "repository_id": { + "name": "repository_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "node_id": { + "name": "node_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "head_branch": { + "name": "head_branch", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "head_sha": { + "name": "head_sha", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "base_branch": { + "name": "base_branch", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "author_login": { + "name": "author_login", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "author_avatar_url": { + "name": "author_avatar_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "is_draft": { + "name": "is_draft", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "additions": { + "name": "additions", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "deletions": { + "name": "deletions", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "changed_files": { + "name": "changed_files", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "review_decision": { + "name": "review_decision", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "checks_status": { + "name": "checks_status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'none'" + }, + "checks": { + "name": "checks", + "type": "jsonb", + "primaryKey": false, + "notNull": false, + "default": "'[]'::jsonb" + }, + "merged_at": { + "name": "merged_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "closed_at": { + "name": "closed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_synced_at": { + "name": "last_synced_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "github_pull_requests_repository_id_idx": { + "name": "github_pull_requests_repository_id_idx", + "columns": [ + { + "expression": "repository_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "github_pull_requests_state_idx": { + "name": "github_pull_requests_state_idx", + "columns": [ + { + "expression": "state", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "github_pull_requests_head_branch_idx": { + "name": "github_pull_requests_head_branch_idx", + "columns": [ + { + "expression": "head_branch", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "github_pull_requests_org_id_idx": { + "name": "github_pull_requests_org_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "github_pull_requests_repository_id_github_repositories_id_fk": { + "name": "github_pull_requests_repository_id_github_repositories_id_fk", + "tableFrom": "github_pull_requests", + "tableTo": "github_repositories", + "columnsFrom": [ + "repository_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "github_pull_requests_organization_id_organizations_id_fk": { + "name": "github_pull_requests_organization_id_organizations_id_fk", + "tableFrom": "github_pull_requests", + "tableTo": "organizations", + "schemaTo": "auth", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "github_pull_requests_repo_pr_unique": { + "name": "github_pull_requests_repo_pr_unique", + "nullsNotDistinct": false, + "columns": [ + "repository_id", + "pr_number" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.github_repositories": { + "name": "github_repositories", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "installation_id": { + "name": "installation_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "repo_id": { + "name": "repo_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "owner": { + "name": "owner", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "full_name": { + "name": "full_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "default_branch": { + "name": "default_branch", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'main'" + }, + "is_private": { + "name": "is_private", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "github_repositories_installation_id_idx": { + "name": "github_repositories_installation_id_idx", + "columns": [ + { + "expression": "installation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "github_repositories_full_name_idx": { + "name": "github_repositories_full_name_idx", + "columns": [ + { + "expression": "full_name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "github_repositories_org_id_idx": { + "name": "github_repositories_org_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "github_repositories_installation_id_github_installations_id_fk": { + "name": "github_repositories_installation_id_github_installations_id_fk", + "tableFrom": "github_repositories", + "tableTo": "github_installations", + "columnsFrom": [ + "installation_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "github_repositories_organization_id_organizations_id_fk": { + "name": "github_repositories_organization_id_organizations_id_fk", + "tableFrom": "github_repositories", + "tableTo": "organizations", + "schemaTo": "auth", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "github_repositories_repo_id_unique": { + "name": "github_repositories_repo_id_unique", + "nullsNotDistinct": false, + "columns": [ + "repo_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "ingest.webhook_events": { + "name": "webhook_events", + "schema": "ingest", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "provider": { + "name": "provider", + "type": "integration_provider", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "event_id": { + "name": "event_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "event_type": { + "name": "event_type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "processed_at": { + "name": "processed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "retry_count": { + "name": "retry_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "received_at": { + "name": "received_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "webhook_events_provider_status_idx": { + "name": "webhook_events_provider_status_idx", + "columns": [ + { + "expression": "provider", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "webhook_events_provider_event_id_idx": { + "name": "webhook_events_provider_event_id_idx", + "columns": [ + { + "expression": "provider", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "event_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "webhook_events_received_at_idx": { + "name": "webhook_events_received_at_idx", + "columns": [ + { + "expression": "received_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.leaderboard_daily": { + "name": "leaderboard_daily", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "day": { + "name": "day", + "type": "date", + "primaryKey": false, + "notNull": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "host_id": { + "name": "host_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "uncached_input": { + "name": "uncached_input", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "cached_input": { + "name": "cached_input", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "cache_write_5m": { + "name": "cache_write_5m", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "cache_write_1h": { + "name": "cache_write_1h", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "output": { + "name": "output", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "reasoning_output": { + "name": "reasoning_output", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "tokens": { + "name": "tokens", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "usd_estimate": { + "name": "usd_estimate", + "type": "numeric(14, 6)", + "primaryKey": false, + "notNull": true, + "default": "'0'" + }, + "approximate": { + "name": "approximate", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "sessions": { + "name": "sessions", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "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": { + "leaderboard_daily_day_idx": { + "name": "leaderboard_daily_day_idx", + "columns": [ + { + "expression": "day", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "leaderboard_daily_user_day_idx": { + "name": "leaderboard_daily_user_day_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "day", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "leaderboard_daily_model_day_idx": { + "name": "leaderboard_daily_model_day_idx", + "columns": [ + { + "expression": "model", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "day", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "leaderboard_daily_user_id_leaderboard_participants_user_id_fk": { + "name": "leaderboard_daily_user_id_leaderboard_participants_user_id_fk", + "tableFrom": "leaderboard_daily", + "tableTo": "leaderboard_participants", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "user_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "leaderboard_daily_identity_key": { + "name": "leaderboard_daily_identity_key", + "nullsNotDistinct": false, + "columns": [ + "user_id", + "day", + "provider", + "model", + "host_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.leaderboard_daily_factory": { + "name": "leaderboard_daily_factory", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "day": { + "name": "day", + "type": "date", + "primaryKey": false, + "notNull": true + }, + "host_id": { + "name": "host_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sessions": { + "name": "sessions", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "parallel_sessions": { + "name": "parallel_sessions", + "type": "numeric(6, 2)", + "primaryKey": false, + "notNull": true, + "default": "'0'" + }, + "agent_prs_merged": { + "name": "agent_prs_merged", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "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": { + "leaderboard_daily_factory_day_idx": { + "name": "leaderboard_daily_factory_day_idx", + "columns": [ + { + "expression": "day", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "leaderboard_daily_factory_user_day_idx": { + "name": "leaderboard_daily_factory_user_day_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "day", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "leaderboard_daily_factory_user_id_leaderboard_participants_user_id_fk": { + "name": "leaderboard_daily_factory_user_id_leaderboard_participants_user_id_fk", + "tableFrom": "leaderboard_daily_factory", + "tableTo": "leaderboard_participants", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "user_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "leaderboard_daily_factory_identity_key": { + "name": "leaderboard_daily_factory_identity_key", + "nullsNotDistinct": false, + "columns": [ + "user_id", + "day", + "host_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.leaderboard_participants": { + "name": "leaderboard_participants", + "schema": "", + "columns": { + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "handle": { + "name": "handle", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "visibility": { + "name": "visibility", + "type": "leaderboard_visibility", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'public'" + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "opted_in_at": { + "name": "opted_in_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "flagged_at": { + "name": "flagged_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_published_at": { + "name": "last_published_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "payload_version": { + "name": "payload_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "tokens": { + "name": "tokens", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "usd": { + "name": "usd", + "type": "numeric(20, 6)", + "primaryKey": false, + "notNull": true, + "default": "'0'" + }, + "sessions": { + "name": "sessions", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "uncached_input": { + "name": "uncached_input", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "cached_input": { + "name": "cached_input", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "cache_write_5m": { + "name": "cache_write_5m", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "cache_write_1h": { + "name": "cache_write_1h", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "output": { + "name": "output", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "reasoning_output": { + "name": "reasoning_output", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "approximate": { + "name": "approximate", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "day_range_start": { + "name": "day_range_start", + "type": "date", + "primaryKey": false, + "notNull": false + }, + "day_range_end": { + "name": "day_range_end", + "type": "date", + "primaryKey": false, + "notNull": false + }, + "tier": { + "name": "tier", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "tier_computed_at": { + "name": "tier_computed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "active_days": { + "name": "active_days", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "axis_width": { + "name": "axis_width", + "type": "numeric(6, 2)", + "primaryKey": false, + "notNull": true, + "default": "'0'" + }, + "axis_depth": { + "name": "axis_depth", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "axis_output": { + "name": "axis_output", + "type": "numeric(8, 2)", + "primaryKey": false, + "notNull": true, + "default": "'0'" + }, + "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": { + "leaderboard_participants_tokens_idx": { + "name": "leaderboard_participants_tokens_idx", + "columns": [ + { + "expression": "tokens", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "leaderboard_participants_org_idx": { + "name": "leaderboard_participants_org_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "leaderboard_participants_usd_idx": { + "name": "leaderboard_participants_usd_idx", + "columns": [ + { + "expression": "usd", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "leaderboard_participants_tier_idx": { + "name": "leaderboard_participants_tier_idx", + "columns": [ + { + "expression": "tier", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "leaderboard_participants_user_id_users_id_fk": { + "name": "leaderboard_participants_user_id_users_id_fk", + "tableFrom": "leaderboard_participants", + "tableTo": "users", + "schemaTo": "auth", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "leaderboard_participants_organization_id_organizations_id_fk": { + "name": "leaderboard_participants_organization_id_organizations_id_fk", + "tableFrom": "leaderboard_participants", + "tableTo": "organizations", + "schemaTo": "auth", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "leaderboard_participants_handle_unique": { + "name": "leaderboard_participants_handle_unique", + "nullsNotDistinct": false, + "columns": [ + "handle" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.agent_commands": { + "name": "agent_commands", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "target_device_id": { + "name": "target_device_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "target_device_type": { + "name": "target_device_type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tool": { + "name": "tool", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "params": { + "name": "params", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "parent_command_id": { + "name": "parent_command_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "command_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "result": { + "name": "result", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "executed_at": { + "name": "executed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "timeout_at": { + "name": "timeout_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "agent_commands_user_status_idx": { + "name": "agent_commands_user_status_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "agent_commands_target_device_status_idx": { + "name": "agent_commands_target_device_status_idx", + "columns": [ + { + "expression": "target_device_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "agent_commands_org_created_idx": { + "name": "agent_commands_org_created_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "agent_commands_user_id_users_id_fk": { + "name": "agent_commands_user_id_users_id_fk", + "tableFrom": "agent_commands", + "tableTo": "users", + "schemaTo": "auth", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "agent_commands_organization_id_organizations_id_fk": { + "name": "agent_commands_organization_id_organizations_id_fk", + "tableFrom": "agent_commands", + "tableTo": "organizations", + "schemaTo": "auth", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.automation_events": { + "name": "automation_events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "integration_connection_id": { + "name": "integration_connection_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "event_type": { + "name": "event_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "external_event_id": { + "name": "external_event_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "resource_key": { + "name": "resource_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "repository_id": { + "name": "repository_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "ref": { + "name": "ref", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "actor_login": { + "name": "actor_login", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "actor_is_external": { + "name": "actor_is_external", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "webhook_event_id": { + "name": "webhook_event_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "received_at": { + "name": "received_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "dispatch_input": { + "name": "dispatch_input", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "dispatched_at": { + "name": "dispatched_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "automation_events_undispatched_idx": { + "name": "automation_events_undispatched_idx", + "columns": [ + { + "expression": "received_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"automation_events\".\"dispatched_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "automation_events_org_received_idx": { + "name": "automation_events_org_received_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "received_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "automation_events_resource_idx": { + "name": "automation_events_resource_idx", + "columns": [ + { + "expression": "resource_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "automation_events_prunable_idx": { + "name": "automation_events_prunable_idx", + "columns": [ + { + "expression": "received_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"automation_events\".\"payload\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "automation_events_organization_id_organizations_id_fk": { + "name": "automation_events_organization_id_organizations_id_fk", + "tableFrom": "automation_events", + "tableTo": "organizations", + "schemaTo": "auth", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "automation_events_integration_connection_id_integration_connections_id_fk": { + "name": "automation_events_integration_connection_id_integration_connections_id_fk", + "tableFrom": "automation_events", + "tableTo": "integration_connections", + "columnsFrom": [ + "integration_connection_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "automation_events_dedup_unique": { + "name": "automation_events_dedup_unique", + "nullsNotDistinct": true, + "columns": [ + "integration_connection_id", + "provider", + "external_event_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.automation_prompt_versions": { + "name": "automation_prompt_versions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "automation_id": { + "name": "automation_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "author_user_id": { + "name": "author_user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "window_bucket": { + "name": "window_bucket", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "content_hash": { + "name": "content_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source": { + "name": "source", + "type": "automation_prompt_source", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "restored_from_version_id": { + "name": "restored_from_version_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "started_at": { + "name": "started_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": { + "automation_prompt_versions_bucket_uniq": { + "name": "automation_prompt_versions_bucket_uniq", + "columns": [ + { + "expression": "automation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "author_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "window_bucket", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"automation_prompt_versions\".\"source\" <> 'restore'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "automation_prompt_versions_automation_idx": { + "name": "automation_prompt_versions_automation_idx", + "columns": [ + { + "expression": "automation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "automation_prompt_versions_automation_id_automations_id_fk": { + "name": "automation_prompt_versions_automation_id_automations_id_fk", + "tableFrom": "automation_prompt_versions", + "tableTo": "automations", + "columnsFrom": [ + "automation_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "automation_prompt_versions_author_user_id_users_id_fk": { + "name": "automation_prompt_versions_author_user_id_users_id_fk", + "tableFrom": "automation_prompt_versions", + "tableTo": "users", + "schemaTo": "auth", + "columnsFrom": [ + "author_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "automation_prompt_versions_restored_from_version_id_fk": { + "name": "automation_prompt_versions_restored_from_version_id_fk", + "tableFrom": "automation_prompt_versions", + "tableTo": "automation_prompt_versions", + "columnsFrom": [ + "restored_from_version_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.automation_runs": { + "name": "automation_runs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "automation_id": { + "name": "automation_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "trigger_id": { + "name": "trigger_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "event_id": { + "name": "event_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "scheduled_for": { + "name": "scheduled_for", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "resource_key": { + "name": "resource_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "host_id": { + "name": "host_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "v2_workspace_id": { + "name": "v2_workspace_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "session_kind": { + "name": "session_kind", + "type": "automation_session_kind", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "chat_session_id": { + "name": "chat_session_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "terminal_session_id": { + "name": "terminal_session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "automation_run_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "dispatched_at": { + "name": "dispatched_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "automation_runs_schedule_dedup_idx": { + "name": "automation_runs_schedule_dedup_idx", + "columns": [ + { + "expression": "automation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "scheduled_for", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "scheduled_for IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "automation_runs_event_dedup_idx": { + "name": "automation_runs_event_dedup_idx", + "columns": [ + { + "expression": "trigger_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "event_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "event_id IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "automation_runs_inflight_resource_idx": { + "name": "automation_runs_inflight_resource_idx", + "columns": [ + { + "expression": "trigger_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "status IN ('dispatching', 'dispatched')", + "concurrently": false, + "method": "btree", + "with": {} + }, + "automation_runs_history_idx": { + "name": "automation_runs_history_idx", + "columns": [ + { + "expression": "automation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "automation_runs_status_idx": { + "name": "automation_runs_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "automation_runs_workspace_idx": { + "name": "automation_runs_workspace_idx", + "columns": [ + { + "expression": "v2_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "automation_runs_organization_id_organizations_id_fk": { + "name": "automation_runs_organization_id_organizations_id_fk", + "tableFrom": "automation_runs", + "tableTo": "organizations", + "schemaTo": "auth", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "automation_runs_trigger_id_automation_triggers_id_fk": { + "name": "automation_runs_trigger_id_automation_triggers_id_fk", + "tableFrom": "automation_runs", + "tableTo": "automation_triggers", + "columnsFrom": [ + "trigger_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "automation_runs_event_id_automation_events_id_fk": { + "name": "automation_runs_event_id_automation_events_id_fk", + "tableFrom": "automation_runs", + "tableTo": "automation_events", + "columnsFrom": [ + "event_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "automation_runs_chat_session_id_chat_sessions_id_fk": { + "name": "automation_runs_chat_session_id_chat_sessions_id_fk", + "tableFrom": "automation_runs", + "tableTo": "chat_sessions", + "columnsFrom": [ + "chat_session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "automation_runs_automation_org_fk": { + "name": "automation_runs_automation_org_fk", + "tableFrom": "automation_runs", + "tableTo": "automations", + "columnsFrom": [ + "automation_id", + "organization_id" + ], + "columnsTo": [ + "id", + "organization_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.automation_triggers": { + "name": "automation_triggers", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "automation_id": { + "name": "automation_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "automation_trigger_kind", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "config": { + "name": "config", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "next_run_at": { + "name": "next_run_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "secret_hash": { + "name": "secret_hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "secret_prefix": { + "name": "secret_prefix", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "secret_rotated_at": { + "name": "secret_rotated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "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": { + "automation_triggers_dispatcher_idx": { + "name": "automation_triggers_dispatcher_idx", + "columns": [ + { + "expression": "next_run_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "kind = 'schedule'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "automation_triggers_matcher_idx": { + "name": "automation_triggers_matcher_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "kind", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "automation_triggers_automation_idx": { + "name": "automation_triggers_automation_idx", + "columns": [ + { + "expression": "automation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "automation_triggers_schedule_idx": { + "name": "automation_triggers_schedule_idx", + "columns": [ + { + "expression": "automation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "kind = 'schedule'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "automation_triggers_organization_id_organizations_id_fk": { + "name": "automation_triggers_organization_id_organizations_id_fk", + "tableFrom": "automation_triggers", + "tableTo": "organizations", + "schemaTo": "auth", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "automation_triggers_automation_org_fk": { + "name": "automation_triggers_automation_org_fk", + "tableFrom": "automation_triggers", + "tableTo": "automations", + "columnsFrom": [ + "automation_id", + "organization_id" + ], + "columnsTo": [ + "id", + "organization_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "automation_triggers_kind_matches_config": { + "name": "automation_triggers_kind_matches_config", + "value": "config->>'kind' = kind::text" + } + }, + "isRLSEnabled": false + }, + "public.automations": { + "name": "automations", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "owner_user_id": { + "name": "owner_user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "prompt": { + "name": "prompt", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "agent": { + "name": "agent", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_host_id": { + "name": "target_host_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "v2_project_id": { + "name": "v2_project_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "v2_workspace_id": { + "name": "v2_workspace_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": 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": { + "automations_owner_idx": { + "name": "automations_owner_idx", + "columns": [ + { + "expression": "owner_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "automations_organization_idx": { + "name": "automations_organization_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "automations_organization_id_organizations_id_fk": { + "name": "automations_organization_id_organizations_id_fk", + "tableFrom": "automations", + "tableTo": "organizations", + "schemaTo": "auth", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "automations_owner_user_id_users_id_fk": { + "name": "automations_owner_user_id_users_id_fk", + "tableFrom": "automations", + "tableTo": "users", + "schemaTo": "auth", + "columnsFrom": [ + "owner_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "automations_id_org_unique": { + "name": "automations_id_org_unique", + "nullsNotDistinct": false, + "columns": [ + "id", + "organization_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.chat_attachments": { + "name": "chat_attachments", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "chat_session_id": { + "name": "chat_session_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "blob_pathname": { + "name": "blob_pathname", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "media_type": { + "name": "media_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "filename": { + "name": "filename", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "size_bytes": { + "name": "size_bytes", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "chat_attachments_session_idx": { + "name": "chat_attachments_session_idx", + "columns": [ + { + "expression": "chat_session_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "chat_attachments_created_by_idx": { + "name": "chat_attachments_created_by_idx", + "columns": [ + { + "expression": "created_by", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "chat_attachments_chat_session_id_chat_sessions_id_fk": { + "name": "chat_attachments_chat_session_id_chat_sessions_id_fk", + "tableFrom": "chat_attachments", + "tableTo": "chat_sessions", + "columnsFrom": [ + "chat_session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "chat_attachments_created_by_users_id_fk": { + "name": "chat_attachments_created_by_users_id_fk", + "tableFrom": "chat_attachments", + "tableTo": "users", + "schemaTo": "auth", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "chat_attachments_organization_id_organizations_id_fk": { + "name": "chat_attachments_organization_id_organizations_id_fk", + "tableFrom": "chat_attachments", + "tableTo": "organizations", + "schemaTo": "auth", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.chat_sessions": { + "name": "chat_sessions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "v2_workspace_id": { + "name": "v2_workspace_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_active_at": { + "name": "last_active_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "chat_sessions_org_idx": { + "name": "chat_sessions_org_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "chat_sessions_created_by_idx": { + "name": "chat_sessions_created_by_idx", + "columns": [ + { + "expression": "created_by", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "chat_sessions_last_active_idx": { + "name": "chat_sessions_last_active_idx", + "columns": [ + { + "expression": "last_active_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "chat_sessions_organization_id_organizations_id_fk": { + "name": "chat_sessions_organization_id_organizations_id_fk", + "tableFrom": "chat_sessions", + "tableTo": "organizations", + "schemaTo": "auth", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "chat_sessions_created_by_users_id_fk": { + "name": "chat_sessions_created_by_users_id_fk", + "tableFrom": "chat_sessions", + "tableTo": "users", + "schemaTo": "auth", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "chat_sessions_workspace_id_workspaces_id_fk": { + "name": "chat_sessions_workspace_id_workspaces_id_fk", + "tableFrom": "chat_sessions", + "tableTo": "workspaces", + "columnsFrom": [ + "workspace_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.cloud_workspaces": { + "name": "cloud_workspaces", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "branch": { + "name": "branch", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'blaxel'" + }, + "provider_sandbox_id": { + "name": "provider_sandbox_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sandbox_url": { + "name": "sandbox_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "cloud_workspace_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'provisioning'" + }, + "created_by_user_id": { + "name": "created_by_user_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "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": { + "cloud_workspaces_organization_id_idx": { + "name": "cloud_workspaces_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "cloud_workspaces_project_id_idx": { + "name": "cloud_workspaces_project_id_idx", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "cloud_workspaces_organization_id_organizations_id_fk": { + "name": "cloud_workspaces_organization_id_organizations_id_fk", + "tableFrom": "cloud_workspaces", + "tableTo": "organizations", + "schemaTo": "auth", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "cloud_workspaces_project_id_v2_projects_id_fk": { + "name": "cloud_workspaces_project_id_v2_projects_id_fk", + "tableFrom": "cloud_workspaces", + "tableTo": "v2_projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "cloud_workspaces_created_by_user_id_users_id_fk": { + "name": "cloud_workspaces_created_by_user_id_users_id_fk", + "tableFrom": "cloud_workspaces", + "tableTo": "users", + "schemaTo": "auth", + "columnsFrom": [ + "created_by_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "cloud_workspaces_provider_sandbox_id_unique": { + "name": "cloud_workspaces_provider_sandbox_id_unique", + "nullsNotDistinct": false, + "columns": [ + "provider", + "provider_sandbox_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.deal_redemptions": { + "name": "deal_redemptions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "external_redemption_id": { + "name": "external_redemption_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "deal_id": { + "name": "deal_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "company_name": { + "name": "company_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "company_batch": { + "name": "company_batch", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "stripe_subscription_id": { + "name": "stripe_subscription_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "promotion_code": { + "name": "promotion_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "deal_redemptions_source_external_id_unique": { + "name": "deal_redemptions_source_external_id_unique", + "columns": [ + { + "expression": "source", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "external_redemption_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "deal_redemptions_email_idx": { + "name": "deal_redemptions_email_idx", + "columns": [ + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "deal_redemptions_organization_id_organizations_id_fk": { + "name": "deal_redemptions_organization_id_organizations_id_fk", + "tableFrom": "deal_redemptions", + "tableTo": "organizations", + "schemaTo": "auth", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.desktop_notices": { + "name": "desktop_notices", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "severity": { + "name": "severity", + "type": "desktop_notice_severity", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "trigger": { + "name": "trigger", + "type": "desktop_notice_trigger", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'immediate'" + }, + "min_version": { + "name": "min_version", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "max_version": { + "name": "max_version", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "platforms": { + "name": "platforms", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "channels": { + "name": "channels", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "starts_at": { + "name": "starts_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "ends_at": { + "name": "ends_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "body": { + "name": "body", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "cta_label": { + "name": "cta_label", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "cta_action": { + "name": "cta_action", + "type": "desktop_notice_cta_action", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "cta_url": { + "name": "cta_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "dismissible": { + "name": "dismissible", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "active": { + "name": "active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "desktop_notices_active_idx": { + "name": "desktop_notices_active_idx", + "columns": [ + { + "expression": "active", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.integration_connections": { + "name": "integration_connections", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "connected_by_user_id": { + "name": "connected_by_user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "provider": { + "name": "provider", + "type": "integration_provider", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "access_token": { + "name": "access_token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "refresh_token": { + "name": "refresh_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "token_expires_at": { + "name": "token_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "disconnected_at": { + "name": "disconnected_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "disconnect_reason": { + "name": "disconnect_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "external_org_id": { + "name": "external_org_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "external_org_name": { + "name": "external_org_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "config": { + "name": "config", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "integration_connections_org_provider_unique": { + "name": "integration_connections_org_provider_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"integration_connections\".\"provider\" <> 'google'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "integration_connections_google_user_unique": { + "name": "integration_connections_google_user_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "connected_by_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"integration_connections\".\"provider\" = 'google'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "integration_connections_slack_external_org_active_unique": { + "name": "integration_connections_slack_external_org_active_unique", + "columns": [ + { + "expression": "external_org_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"integration_connections\".\"provider\" = 'slack' AND \"integration_connections\".\"disconnected_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "integration_connections_org_idx": { + "name": "integration_connections_org_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "integration_connections_organization_id_organizations_id_fk": { + "name": "integration_connections_organization_id_organizations_id_fk", + "tableFrom": "integration_connections", + "tableTo": "organizations", + "schemaTo": "auth", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "integration_connections_connected_by_user_id_users_id_fk": { + "name": "integration_connections_connected_by_user_id_users_id_fk", + "tableFrom": "integration_connections", + "tableTo": "users", + "schemaTo": "auth", + "columnsFrom": [ + "connected_by_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.page_comment_threads": { + "name": "page_comment_threads", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "page_id": { + "name": "page_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "page_version_id": { + "name": "page_version_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "anchor_kind": { + "name": "anchor_kind", + "type": "page_comment_anchor_kind", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "anchor": { + "name": "anchor", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "anchor_text": { + "name": "anchor_text", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_by_user_id": { + "name": "created_by_user_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "agent_activated_at": { + "name": "agent_activated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "agent_activated_by_user_id": { + "name": "agent_activated_by_user_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "resolved_at": { + "name": "resolved_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "resolved_by_user_id": { + "name": "resolved_by_user_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "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": { + "page_comment_threads_page_id_idx": { + "name": "page_comment_threads_page_id_idx", + "columns": [ + { + "expression": "page_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "page_comment_threads_page_version_id_idx": { + "name": "page_comment_threads_page_version_id_idx", + "columns": [ + { + "expression": "page_version_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "page_comment_threads_open_idx": { + "name": "page_comment_threads_open_idx", + "columns": [ + { + "expression": "page_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "resolved_at IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "page_comment_threads_page_id_pages_id_fk": { + "name": "page_comment_threads_page_id_pages_id_fk", + "tableFrom": "page_comment_threads", + "tableTo": "pages", + "columnsFrom": [ + "page_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "page_comment_threads_page_version_id_page_versions_id_fk": { + "name": "page_comment_threads_page_version_id_page_versions_id_fk", + "tableFrom": "page_comment_threads", + "tableTo": "page_versions", + "columnsFrom": [ + "page_version_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "page_comment_threads_created_by_user_id_users_id_fk": { + "name": "page_comment_threads_created_by_user_id_users_id_fk", + "tableFrom": "page_comment_threads", + "tableTo": "users", + "schemaTo": "auth", + "columnsFrom": [ + "created_by_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "page_comment_threads_agent_activated_by_user_id_users_id_fk": { + "name": "page_comment_threads_agent_activated_by_user_id_users_id_fk", + "tableFrom": "page_comment_threads", + "tableTo": "users", + "schemaTo": "auth", + "columnsFrom": [ + "agent_activated_by_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "page_comment_threads_resolved_by_user_id_users_id_fk": { + "name": "page_comment_threads_resolved_by_user_id_users_id_fk", + "tableFrom": "page_comment_threads", + "tableTo": "users", + "schemaTo": "auth", + "columnsFrom": [ + "resolved_by_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "page_comment_threads_anchor_matches_kind": { + "name": "page_comment_threads_anchor_matches_kind", + "value": "(anchor_kind = 'page') = (anchor IS NULL)" + } + }, + "isRLSEnabled": false + }, + "public.page_comments": { + "name": "page_comments", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "thread_id": { + "name": "thread_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "author_kind": { + "name": "author_kind", + "type": "page_comment_author_kind", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'human'" + }, + "author_user_id": { + "name": "author_user_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "agent_session_id": { + "name": "agent_session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "body": { + "name": "body", + "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()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "page_comments_thread_id_created_at_idx": { + "name": "page_comments_thread_id_created_at_idx", + "columns": [ + { + "expression": "thread_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "page_comments_thread_id_page_comment_threads_id_fk": { + "name": "page_comments_thread_id_page_comment_threads_id_fk", + "tableFrom": "page_comments", + "tableTo": "page_comment_threads", + "columnsFrom": [ + "thread_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "page_comments_author_user_id_users_id_fk": { + "name": "page_comments_author_user_id_users_id_fk", + "tableFrom": "page_comments", + "tableTo": "users", + "schemaTo": "auth", + "columnsFrom": [ + "author_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "page_comments_agent_has_session": { + "name": "page_comments_agent_has_session", + "value": "author_kind <> 'agent' OR agent_session_id IS NOT NULL" + } + }, + "isRLSEnabled": false + }, + "public.page_versions": { + "name": "page_versions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "page_id": { + "name": "page_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "blob_pathname": { + "name": "blob_pathname", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "content_type": { + "name": "content_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "size_bytes": { + "name": "size_bytes", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "sha256": { + "name": "sha256", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "created_by_user_id": { + "name": "created_by_user_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "page_versions_page_id_idx": { + "name": "page_versions_page_id_idx", + "columns": [ + { + "expression": "page_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "page_versions_page_id_pages_id_fk": { + "name": "page_versions_page_id_pages_id_fk", + "tableFrom": "page_versions", + "tableTo": "pages", + "columnsFrom": [ + "page_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "page_versions_created_by_user_id_users_id_fk": { + "name": "page_versions_created_by_user_id_users_id_fk", + "tableFrom": "page_versions", + "tableTo": "users", + "schemaTo": "auth", + "columnsFrom": [ + "created_by_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "page_versions_page_id_version_unique": { + "name": "page_versions_page_id_version_unique", + "nullsNotDistinct": false, + "columns": [ + "page_id", + "version" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.pages": { + "name": "pages", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_by_user_id": { + "name": "created_by_user_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "visibility": { + "name": "visibility", + "type": "page_visibility", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'just_me'" + }, + "shared_version": { + "name": "shared_version", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "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": { + "pages_slug_unique": { + "name": "pages_slug_unique", + "columns": [ + { + "expression": "slug", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "pages_organization_id_updated_at_idx": { + "name": "pages_organization_id_updated_at_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "\"updated_at\" desc", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "pages_created_by_user_id_idx": { + "name": "pages_created_by_user_id_idx", + "columns": [ + { + "expression": "created_by_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "pages_organization_id_organizations_id_fk": { + "name": "pages_organization_id_organizations_id_fk", + "tableFrom": "pages", + "tableTo": "organizations", + "schemaTo": "auth", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "pages_created_by_user_id_users_id_fk": { + "name": "pages_created_by_user_id_users_id_fk", + "tableFrom": "pages", + "tableTo": "users", + "schemaTo": "auth", + "columnsFrom": [ + "created_by_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.projects": { + "name": "projects", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "github_repository_id": { + "name": "github_repository_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "repo_owner": { + "name": "repo_owner", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "repo_name": { + "name": "repo_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "repo_url": { + "name": "repo_url", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "default_branch": { + "name": "default_branch", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'main'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "projects_organization_id_idx": { + "name": "projects_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "projects_organization_id_organizations_id_fk": { + "name": "projects_organization_id_organizations_id_fk", + "tableFrom": "projects", + "tableTo": "organizations", + "schemaTo": "auth", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "projects_github_repository_id_github_repositories_id_fk": { + "name": "projects_github_repository_id_github_repositories_id_fk", + "tableFrom": "projects", + "tableTo": "github_repositories", + "columnsFrom": [ + "github_repository_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "projects_org_slug_unique": { + "name": "projects_org_slug_unique", + "nullsNotDistinct": false, + "columns": [ + "organization_id", + "slug" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.submitted_prompts": { + "name": "submitted_prompts", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "prompt_text": { + "name": "prompt_text", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "submitter_name": { + "name": "submitter_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "submitted_prompts_user_id_idx": { + "name": "submitted_prompts_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "submitted_prompts_organization_id_idx": { + "name": "submitted_prompts_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "submitted_prompts_created_at_idx": { + "name": "submitted_prompts_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "submitted_prompts_user_id_users_id_fk": { + "name": "submitted_prompts_user_id_users_id_fk", + "tableFrom": "submitted_prompts", + "tableTo": "users", + "schemaTo": "auth", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "submitted_prompts_organization_id_organizations_id_fk": { + "name": "submitted_prompts_organization_id_organizations_id_fk", + "tableFrom": "submitted_prompts", + "tableTo": "organizations", + "schemaTo": "auth", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.subscriptions": { + "name": "subscriptions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "plan": { + "name": "plan", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "reference_id": { + "name": "reference_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "stripe_customer_id": { + "name": "stripe_customer_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "stripe_subscription_id": { + "name": "stripe_subscription_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'incomplete'" + }, + "period_start": { + "name": "period_start", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "period_end": { + "name": "period_end", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "trial_start": { + "name": "trial_start", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "trial_end": { + "name": "trial_end", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "cancel_at_period_end": { + "name": "cancel_at_period_end", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": false + }, + "cancel_at": { + "name": "cancel_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "canceled_at": { + "name": "canceled_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "ended_at": { + "name": "ended_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "seats": { + "name": "seats", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "billing_interval": { + "name": "billing_interval", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "stripe_schedule_id": { + "name": "stripe_schedule_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "subscriptions_reference_id_idx": { + "name": "subscriptions_reference_id_idx", + "columns": [ + { + "expression": "reference_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "subscriptions_stripe_customer_id_idx": { + "name": "subscriptions_stripe_customer_id_idx", + "columns": [ + { + "expression": "stripe_customer_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "subscriptions_status_idx": { + "name": "subscriptions_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "subscriptions_reference_id_organizations_id_fk": { + "name": "subscriptions_reference_id_organizations_id_fk", + "tableFrom": "subscriptions", + "tableTo": "organizations", + "schemaTo": "auth", + "columnsFrom": [ + "reference_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.task_statuses": { + "name": "task_statuses", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "color": { + "name": "color", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "position": { + "name": "position", + "type": "real", + "primaryKey": false, + "notNull": true + }, + "progress_percent": { + "name": "progress_percent", + "type": "real", + "primaryKey": false, + "notNull": false + }, + "external_provider": { + "name": "external_provider", + "type": "integration_provider", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "external_id": { + "name": "external_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "task_statuses_organization_id_idx": { + "name": "task_statuses_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "task_statuses_type_idx": { + "name": "task_statuses_type_idx", + "columns": [ + { + "expression": "type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "task_statuses_organization_id_organizations_id_fk": { + "name": "task_statuses_organization_id_organizations_id_fk", + "tableFrom": "task_statuses", + "tableTo": "organizations", + "schemaTo": "auth", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "task_statuses_org_external_unique": { + "name": "task_statuses_org_external_unique", + "nullsNotDistinct": false, + "columns": [ + "organization_id", + "external_provider", + "external_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.tasks": { + "name": "tasks", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status_id": { + "name": "status_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "priority": { + "name": "priority", + "type": "task_priority", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'none'" + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "assignee_id": { + "name": "assignee_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "creator_id": { + "name": "creator_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "estimate": { + "name": "estimate", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "due_date": { + "name": "due_date", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "labels": { + "name": "labels", + "type": "jsonb", + "primaryKey": false, + "notNull": false, + "default": "'[]'::jsonb" + }, + "branch": { + "name": "branch", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "pr_url": { + "name": "pr_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "external_provider": { + "name": "external_provider", + "type": "integration_provider", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "external_id": { + "name": "external_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "external_key": { + "name": "external_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "external_url": { + "name": "external_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_synced_at": { + "name": "last_synced_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "sync_error": { + "name": "sync_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "external_updated_at": { + "name": "external_updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "external_project_id": { + "name": "external_project_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "external_project_name": { + "name": "external_project_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "external_cycle_id": { + "name": "external_cycle_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "external_cycle_name": { + "name": "external_cycle_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "assignee_external_id": { + "name": "assignee_external_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "assignee_display_name": { + "name": "assignee_display_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "assignee_avatar_url": { + "name": "assignee_avatar_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "tasks_slug_idx": { + "name": "tasks_slug_idx", + "columns": [ + { + "expression": "slug", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "tasks_organization_id_idx": { + "name": "tasks_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "tasks_assignee_id_idx": { + "name": "tasks_assignee_id_idx", + "columns": [ + { + "expression": "assignee_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "tasks_creator_id_idx": { + "name": "tasks_creator_id_idx", + "columns": [ + { + "expression": "creator_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "tasks_status_id_idx": { + "name": "tasks_status_id_idx", + "columns": [ + { + "expression": "status_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "tasks_created_at_idx": { + "name": "tasks_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "tasks_external_provider_idx": { + "name": "tasks_external_provider_idx", + "columns": [ + { + "expression": "external_provider", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "tasks_external_project_id_idx": { + "name": "tasks_external_project_id_idx", + "columns": [ + { + "expression": "external_project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "tasks_external_project_name_idx": { + "name": "tasks_external_project_name_idx", + "columns": [ + { + "expression": "external_project_name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "tasks_external_cycle_id_idx": { + "name": "tasks_external_cycle_id_idx", + "columns": [ + { + "expression": "external_cycle_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "tasks_assignee_external_id_idx": { + "name": "tasks_assignee_external_id_idx", + "columns": [ + { + "expression": "assignee_external_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "tasks_status_id_task_statuses_id_fk": { + "name": "tasks_status_id_task_statuses_id_fk", + "tableFrom": "tasks", + "tableTo": "task_statuses", + "columnsFrom": [ + "status_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "tasks_organization_id_organizations_id_fk": { + "name": "tasks_organization_id_organizations_id_fk", + "tableFrom": "tasks", + "tableTo": "organizations", + "schemaTo": "auth", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "tasks_assignee_id_users_id_fk": { + "name": "tasks_assignee_id_users_id_fk", + "tableFrom": "tasks", + "tableTo": "users", + "schemaTo": "auth", + "columnsFrom": [ + "assignee_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "tasks_creator_id_users_id_fk": { + "name": "tasks_creator_id_users_id_fk", + "tableFrom": "tasks", + "tableTo": "users", + "schemaTo": "auth", + "columnsFrom": [ + "creator_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "tasks_external_unique": { + "name": "tasks_external_unique", + "nullsNotDistinct": false, + "columns": [ + "organization_id", + "external_provider", + "external_id" + ] + }, + "tasks_org_slug_unique": { + "name": "tasks_org_slug_unique", + "nullsNotDistinct": false, + "columns": [ + "organization_id", + "slug" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.user_identities": { + "name": "user_identities", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "external_id": { + "name": "external_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "external_scope_id": { + "name": "external_scope_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "handle": { + "name": "handle", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "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": { + "user_identities_user_idx": { + "name": "user_identities_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "user_identities_org_provider_idx": { + "name": "user_identities_org_provider_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "user_identities_user_id_users_id_fk": { + "name": "user_identities_user_id_users_id_fk", + "tableFrom": "user_identities", + "tableTo": "users", + "schemaTo": "auth", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "user_identities_organization_id_organizations_id_fk": { + "name": "user_identities_organization_id_organizations_id_fk", + "tableFrom": "user_identities", + "tableTo": "organizations", + "schemaTo": "auth", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "user_identities_account_unique": { + "name": "user_identities_account_unique", + "nullsNotDistinct": true, + "columns": [ + "organization_id", + "provider", + "external_scope_id", + "external_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.v2_clients": { + "name": "v2_clients", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "machine_id": { + "name": "machine_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "type": { + "name": "type", + "type": "v2_client_type", + "typeSchema": "public", + "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": { + "v2_clients_organization_id_idx": { + "name": "v2_clients_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "v2_clients_user_id_idx": { + "name": "v2_clients_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "v2_clients_organization_id_organizations_id_fk": { + "name": "v2_clients_organization_id_organizations_id_fk", + "tableFrom": "v2_clients", + "tableTo": "organizations", + "schemaTo": "auth", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "v2_clients_user_id_users_id_fk": { + "name": "v2_clients_user_id_users_id_fk", + "tableFrom": "v2_clients", + "tableTo": "users", + "schemaTo": "auth", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "v2_clients_organization_id_user_id_machine_id_pk": { + "name": "v2_clients_organization_id_user_id_machine_id_pk", + "columns": [ + "organization_id", + "user_id", + "machine_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.v2_hosts": { + "name": "v2_hosts", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "machine_id": { + "name": "machine_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "is_online": { + "name": "is_online", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "wake_command": { + "name": "wake_command", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_by_user_id": { + "name": "created_by_user_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "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": { + "v2_hosts_organization_id_idx": { + "name": "v2_hosts_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "v2_hosts_organization_id_organizations_id_fk": { + "name": "v2_hosts_organization_id_organizations_id_fk", + "tableFrom": "v2_hosts", + "tableTo": "organizations", + "schemaTo": "auth", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "v2_hosts_created_by_user_id_users_id_fk": { + "name": "v2_hosts_created_by_user_id_users_id_fk", + "tableFrom": "v2_hosts", + "tableTo": "users", + "schemaTo": "auth", + "columnsFrom": [ + "created_by_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "v2_hosts_organization_id_machine_id_pk": { + "name": "v2_hosts_organization_id_machine_id_pk", + "columns": [ + "organization_id", + "machine_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.v2_projects": { + "name": "v2_projects", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "repo_clone_url": { + "name": "repo_clone_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "github_repository_id": { + "name": "github_repository_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "icon_url": { + "name": "icon_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "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": { + "v2_projects_organization_id_idx": { + "name": "v2_projects_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "v2_projects_organization_id_organizations_id_fk": { + "name": "v2_projects_organization_id_organizations_id_fk", + "tableFrom": "v2_projects", + "tableTo": "organizations", + "schemaTo": "auth", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "v2_projects_github_repository_id_github_repositories_id_fk": { + "name": "v2_projects_github_repository_id_github_repositories_id_fk", + "tableFrom": "v2_projects", + "tableTo": "github_repositories", + "columnsFrom": [ + "github_repository_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "v2_projects_org_slug_unique": { + "name": "v2_projects_org_slug_unique", + "nullsNotDistinct": false, + "columns": [ + "organization_id", + "slug" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.v2_users_hosts": { + "name": "v2_users_hosts", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "host_id": { + "name": "host_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "role": { + "name": "role", + "type": "v2_users_host_role", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'member'" + }, + "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": { + "v2_users_hosts_organization_id_idx": { + "name": "v2_users_hosts_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "v2_users_hosts_user_id_idx": { + "name": "v2_users_hosts_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "v2_users_hosts_host_id_idx": { + "name": "v2_users_hosts_host_id_idx", + "columns": [ + { + "expression": "host_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "v2_users_hosts_organization_id_organizations_id_fk": { + "name": "v2_users_hosts_organization_id_organizations_id_fk", + "tableFrom": "v2_users_hosts", + "tableTo": "organizations", + "schemaTo": "auth", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "v2_users_hosts_user_id_users_id_fk": { + "name": "v2_users_hosts_user_id_users_id_fk", + "tableFrom": "v2_users_hosts", + "tableTo": "users", + "schemaTo": "auth", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "v2_users_hosts_host_fk": { + "name": "v2_users_hosts_host_fk", + "tableFrom": "v2_users_hosts", + "tableTo": "v2_hosts", + "columnsFrom": [ + "organization_id", + "host_id" + ], + "columnsTo": [ + "organization_id", + "machine_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "v2_users_hosts_organization_id_user_id_host_id_pk": { + "name": "v2_users_hosts_organization_id_user_id_host_id_pk", + "columns": [ + "organization_id", + "user_id", + "host_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.v2_workspaces": { + "name": "v2_workspaces", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "host_id": { + "name": "host_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "branch": { + "name": "branch", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "type": { + "name": "type", + "type": "v2_workspace_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'worktree'" + }, + "created_by_user_id": { + "name": "created_by_user_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "task_id": { + "name": "task_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "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": { + "v2_workspaces_project_id_idx": { + "name": "v2_workspaces_project_id_idx", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "v2_workspaces_organization_id_idx": { + "name": "v2_workspaces_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "v2_workspaces_host_id_idx": { + "name": "v2_workspaces_host_id_idx", + "columns": [ + { + "expression": "host_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "v2_workspaces_task_id_idx": { + "name": "v2_workspaces_task_id_idx", + "columns": [ + { + "expression": "task_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "v2_workspaces_one_main_per_host": { + "name": "v2_workspaces_one_main_per_host", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "host_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"v2_workspaces\".\"type\" = 'main'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "v2_workspaces_organization_id_organizations_id_fk": { + "name": "v2_workspaces_organization_id_organizations_id_fk", + "tableFrom": "v2_workspaces", + "tableTo": "organizations", + "schemaTo": "auth", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "v2_workspaces_created_by_user_id_users_id_fk": { + "name": "v2_workspaces_created_by_user_id_users_id_fk", + "tableFrom": "v2_workspaces", + "tableTo": "users", + "schemaTo": "auth", + "columnsFrom": [ + "created_by_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "v2_workspaces_task_id_tasks_id_fk": { + "name": "v2_workspaces_task_id_tasks_id_fk", + "tableFrom": "v2_workspaces", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "v2_workspaces_host_fk": { + "name": "v2_workspaces_host_fk", + "tableFrom": "v2_workspaces", + "tableTo": "v2_hosts", + "columnsFrom": [ + "organization_id", + "host_id" + ], + "columnsTo": [ + "organization_id", + "machine_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_pages": { + "name": "workspace_pages", + "schema": "", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "page_id": { + "name": "page_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "entry_path": { + "name": "entry_path", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspace_pages_workspace_id_entry_path_unique": { + "name": "workspace_pages_workspace_id_entry_path_unique", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "entry_path", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_pages_page_id_idx": { + "name": "workspace_pages_page_id_idx", + "columns": [ + { + "expression": "page_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_pages_page_id_pages_id_fk": { + "name": "workspace_pages_page_id_pages_id_fk", + "tableFrom": "workspace_pages", + "tableTo": "pages", + "columnsFrom": [ + "page_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "workspace_pages_workspace_id_page_id_pk": { + "name": "workspace_pages_workspace_id_page_id_pk", + "columns": [ + "workspace_id", + "page_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspaces": { + "name": "workspaces", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "type": { + "name": "type", + "type": "workspace_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "config": { + "name": "config", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_by_user_id": { + "name": "created_by_user_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "workspaces_project_id_idx": { + "name": "workspaces_project_id_idx", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspaces_organization_id_idx": { + "name": "workspaces_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspaces_type_idx": { + "name": "workspaces_type_idx", + "columns": [ + { + "expression": "type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspaces_organization_id_organizations_id_fk": { + "name": "workspaces_organization_id_organizations_id_fk", + "tableFrom": "workspaces", + "tableTo": "organizations", + "schemaTo": "auth", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspaces_project_id_projects_id_fk": { + "name": "workspaces_project_id_projects_id_fk", + "tableFrom": "workspaces", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspaces_created_by_user_id_users_id_fk": { + "name": "workspaces_created_by_user_id_users_id_fk", + "tableFrom": "workspaces", + "tableTo": "users", + "schemaTo": "auth", + "columnsFrom": [ + "created_by_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": { + "public.leaderboard_visibility": { + "name": "leaderboard_visibility", + "schema": "public", + "values": [ + "public", + "hidden" + ] + }, + "public.automation_prompt_source": { + "name": "automation_prompt_source", + "schema": "public", + "values": [ + "human", + "agent", + "restore" + ] + }, + "public.automation_run_status": { + "name": "automation_run_status", + "schema": "public", + "values": [ + "dispatching", + "dispatched", + "skipped_offline", + "dispatch_failed", + "debounced", + "rejected" + ] + }, + "public.automation_session_kind": { + "name": "automation_session_kind", + "schema": "public", + "values": [ + "chat", + "terminal" + ] + }, + "public.automation_trigger_kind": { + "name": "automation_trigger_kind", + "schema": "public", + "values": [ + "schedule", + "webhook", + "github", + "slack", + "linear", + "sentry", + "microsoft_teams", + "google_calendar", + "gmail", + "notion", + "circleback" + ] + }, + "public.cloud_workspace_status": { + "name": "cloud_workspace_status", + "schema": "public", + "values": [ + "provisioning", + "ready", + "failed", + "deleted" + ] + }, + "public.command_status": { + "name": "command_status", + "schema": "public", + "values": [ + "pending", + "completed", + "failed", + "timeout" + ] + }, + "public.desktop_notice_cta_action": { + "name": "desktop_notice_cta_action", + "schema": "public", + "values": [ + "install-update", + "open-url" + ] + }, + "public.desktop_notice_severity": { + "name": "desktop_notice_severity", + "schema": "public", + "values": [ + "info", + "warning", + "blocking" + ] + }, + "public.desktop_notice_trigger": { + "name": "desktop_notice_trigger", + "schema": "public", + "values": [ + "immediate", + "pre-update", + "post-update" + ] + }, + "public.integration_provider": { + "name": "integration_provider", + "schema": "public", + "values": [ + "linear", + "github", + "slack", + "sentry", + "microsoft_teams", + "google", + "notion" + ] + }, + "public.page_comment_anchor_kind": { + "name": "page_comment_anchor_kind", + "schema": "public", + "values": [ + "element", + "text", + "page" + ] + }, + "public.page_comment_author_kind": { + "name": "page_comment_author_kind", + "schema": "public", + "values": [ + "human", + "agent" + ] + }, + "public.page_visibility": { + "name": "page_visibility", + "schema": "public", + "values": [ + "just_me", + "org", + "everyone" + ] + }, + "public.task_priority": { + "name": "task_priority", + "schema": "public", + "values": [ + "urgent", + "high", + "medium", + "low", + "none" + ] + }, + "public.task_status": { + "name": "task_status", + "schema": "public", + "values": [ + "backlog", + "todo", + "planning", + "working", + "needs-feedback", + "ready-to-merge", + "completed", + "canceled" + ] + }, + "public.v2_client_type": { + "name": "v2_client_type", + "schema": "public", + "values": [ + "desktop", + "mobile", + "web" + ] + }, + "public.v2_users_host_role": { + "name": "v2_users_host_role", + "schema": "public", + "values": [ + "owner", + "member" + ] + }, + "public.v2_workspace_type": { + "name": "v2_workspace_type", + "schema": "public", + "values": [ + "main", + "worktree" + ] + }, + "public.workspace_type": { + "name": "workspace_type", + "schema": "public", + "values": [ + "local", + "cloud" + ] + } + }, + "schemas": { + "auth": "auth", + "ingest": "ingest" + }, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/packages/db/drizzle/meta/_journal.json b/packages/db/drizzle/meta/_journal.json index c8928718463..2e2eb3ad5c9 100644 --- a/packages/db/drizzle/meta/_journal.json +++ b/packages/db/drizzle/meta/_journal.json @@ -659,6 +659,13 @@ "when": 1787673566186, "tag": "0093_deal_redemptions", "breakpoints": true + }, + { + "idx": 94, + "version": "7", + "when": 1787720351737, + "tag": "0094_add_leaderboard_and_tier_tables", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema/enums.ts b/packages/db/src/schema/enums.ts index db86c2c467d..9282c6af7e1 100644 --- a/packages/db/src/schema/enums.ts +++ b/packages/db/src/schema/enums.ts @@ -161,3 +161,7 @@ export type PageCommentAnchorKind = z.infer; export const pageCommentAuthorKindValues = ["human", "agent"] as const; export const pageCommentAuthorKindEnum = z.enum(pageCommentAuthorKindValues); export type PageCommentAuthorKind = z.infer; + +export const leaderboardVisibilityValues = ["public", "hidden"] as const; +export const leaderboardVisibilityEnum = z.enum(leaderboardVisibilityValues); +export type LeaderboardVisibility = z.infer; diff --git a/packages/db/src/schema/index.ts b/packages/db/src/schema/index.ts index 3710ee6afd9..93860c7388b 100644 --- a/packages/db/src/schema/index.ts +++ b/packages/db/src/schema/index.ts @@ -2,6 +2,7 @@ export * from "./auth"; export * from "./enums"; export * from "./github"; export * from "./ingest"; +export * from "./leaderboard"; export * from "./relations"; export * from "./schema"; export * from "./types"; diff --git a/packages/db/src/schema/leaderboard.ts b/packages/db/src/schema/leaderboard.ts new file mode 100644 index 00000000000..533c5760a66 --- /dev/null +++ b/packages/db/src/schema/leaderboard.ts @@ -0,0 +1,215 @@ +import { + bigint, + boolean, + date, + index, + integer, + numeric, + pgEnum, + pgTable, + text, + timestamp, + unique, + uuid, +} from "drizzle-orm/pg-core"; +import { organizations, users } from "./auth"; +import { leaderboardVisibilityValues } from "./enums"; + +export const leaderboardVisibility = pgEnum( + "leaderboard_visibility", + leaderboardVisibilityValues, +); + +export const leaderboardParticipants = pgTable( + "leaderboard_participants", + { + userId: uuid("user_id") + .primaryKey() + .references(() => users.id, { onDelete: "cascade" }), + + handle: text().notNull().unique(), + visibility: leaderboardVisibility().notNull().default("public"), + + organizationId: uuid("organization_id").references(() => organizations.id, { + onDelete: "set null", + }), + + optedInAt: timestamp("opted_in_at", { withTimezone: true }) + .notNull() + .defaultNow(), + revokedAt: timestamp("revoked_at", { withTimezone: true }), + // Shadow lever: publish still succeeds, but the board queries exclude the + // participant. Distinct from revokedAt, which rejects the publish outright. + flaggedAt: timestamp("flagged_at", { withTimezone: true }), + lastPublishedAt: timestamp("last_published_at", { withTimezone: true }), + + payloadVersion: integer("payload_version").notNull().default(1), + + tokens: bigint({ mode: "number" }).notNull().default(0), + usd: numeric({ precision: 20, scale: 6 }).notNull().default("0"), + sessions: integer().notNull().default(0), + + uncachedInput: bigint("uncached_input", { mode: "number" }) + .notNull() + .default(0), + cachedInput: bigint("cached_input", { mode: "number" }) + .notNull() + .default(0), + cacheWrite5m: bigint("cache_write_5m", { mode: "number" }) + .notNull() + .default(0), + cacheWrite1h: bigint("cache_write_1h", { mode: "number" }) + .notNull() + .default(0), + output: bigint({ mode: "number" }).notNull().default(0), + reasoningOutput: bigint("reasoning_output", { mode: "number" }) + .notNull() + .default(0), + + approximate: boolean().notNull().default(false), + + dayRangeStart: date("day_range_start"), + dayRangeEnd: date("day_range_end"), + + tier: integer().notNull().default(0), + tierComputedAt: timestamp("tier_computed_at", { withTimezone: true }), + activeDays: integer("active_days").notNull().default(0), + axisWidth: numeric("axis_width", { precision: 6, scale: 2 }) + .notNull() + .default("0"), + axisDepth: bigint("axis_depth", { mode: "number" }).notNull().default(0), + axisOutput: numeric("axis_output", { precision: 8, scale: 2 }) + .notNull() + .default("0"), + + createdAt: timestamp("created_at", { withTimezone: true }) + .notNull() + .defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }) + .notNull() + .defaultNow() + .$onUpdate(() => new Date()), + }, + (table) => [ + index("leaderboard_participants_tokens_idx").on(table.tokens), + index("leaderboard_participants_org_idx").on(table.organizationId), + index("leaderboard_participants_usd_idx").on(table.usd), + index("leaderboard_participants_tier_idx").on(table.tier), + ], +); + +export type SelectLeaderboardParticipant = + typeof leaderboardParticipants.$inferSelect; +export type InsertLeaderboardParticipant = + typeof leaderboardParticipants.$inferInsert; + +export const leaderboardDaily = pgTable( + "leaderboard_daily", + { + id: uuid().primaryKey().defaultRandom(), + userId: uuid("user_id") + .notNull() + .references(() => leaderboardParticipants.userId, { + onDelete: "cascade", + }), + + day: date().notNull(), + provider: text().notNull(), + model: text().notNull(), + hostId: text("host_id").notNull(), + + uncachedInput: bigint("uncached_input", { mode: "number" }) + .notNull() + .default(0), + cachedInput: bigint("cached_input", { mode: "number" }) + .notNull() + .default(0), + cacheWrite5m: bigint("cache_write_5m", { mode: "number" }) + .notNull() + .default(0), + cacheWrite1h: bigint("cache_write_1h", { mode: "number" }) + .notNull() + .default(0), + output: bigint({ mode: "number" }).notNull().default(0), + + reasoningOutput: bigint("reasoning_output", { mode: "number" }) + .notNull() + .default(0), + tokens: bigint({ mode: "number" }).notNull().default(0), + + usdEstimate: numeric("usd_estimate", { precision: 14, scale: 6 }) + .notNull() + .default("0"), + approximate: boolean().notNull().default(false), + + sessions: integer().notNull().default(0), + + createdAt: timestamp("created_at", { withTimezone: true }) + .notNull() + .defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }) + .notNull() + .defaultNow() + .$onUpdate(() => new Date()), + }, + (table) => [ + unique("leaderboard_daily_identity_key").on( + table.userId, + table.day, + table.provider, + table.model, + table.hostId, + ), + + index("leaderboard_daily_day_idx").on(table.day), + index("leaderboard_daily_user_day_idx").on(table.userId, table.day), + index("leaderboard_daily_model_day_idx").on(table.model, table.day), + ], +); + +export type SelectLeaderboardDaily = typeof leaderboardDaily.$inferSelect; +export type InsertLeaderboardDaily = typeof leaderboardDaily.$inferInsert; + +export const leaderboardDailyFactory = pgTable( + "leaderboard_daily_factory", + { + id: uuid().primaryKey().defaultRandom(), + userId: uuid("user_id") + .notNull() + .references(() => leaderboardParticipants.userId, { + onDelete: "cascade", + }), + + day: date().notNull(), + hostId: text("host_id").notNull(), + + sessions: integer().notNull().default(0), + + parallelSessions: numeric("parallel_sessions", { precision: 6, scale: 2 }) + .notNull() + .default("0"), + agentPrsMerged: integer("agent_prs_merged").notNull().default(0), + + createdAt: timestamp("created_at", { withTimezone: true }) + .notNull() + .defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }) + .notNull() + .defaultNow() + .$onUpdate(() => new Date()), + }, + (table) => [ + unique("leaderboard_daily_factory_identity_key").on( + table.userId, + table.day, + table.hostId, + ), + index("leaderboard_daily_factory_day_idx").on(table.day), + index("leaderboard_daily_factory_user_day_idx").on(table.userId, table.day), + ], +); + +export type SelectLeaderboardDailyFactory = + typeof leaderboardDailyFactory.$inferSelect; +export type InsertLeaderboardDailyFactory = + typeof leaderboardDailyFactory.$inferInsert; diff --git a/packages/host-service/src/trpc/router/usage/history/agent-prs.ts b/packages/host-service/src/trpc/router/usage/history/agent-prs.ts new file mode 100644 index 00000000000..0d6808755db --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/history/agent-prs.ts @@ -0,0 +1,43 @@ +import { and, eq, gte, isNotNull } from "drizzle-orm"; +import type { HostDb } from "../../../../db"; +import { + pullRequests, + terminalAgentBindings, + workspacePullRequests, +} from "../../../../db/schema"; +import { utcMidnightCutoff } from "./leaderboard-days"; + +export function countAgentPrsByDay( + db: HostDb, + days: number, + now: Date = new Date(), +): Record { + const cutoff = utcMidnightCutoff(days, now); + + const rows = db + .selectDistinct({ + pullRequestId: pullRequests.id, + mergedAt: pullRequests.mergedAt, + }) + .from(pullRequests) + .innerJoin( + workspacePullRequests, + eq(workspacePullRequests.pullRequestId, pullRequests.id), + ) + .innerJoin( + terminalAgentBindings, + eq(terminalAgentBindings.workspaceId, workspacePullRequests.workspaceId), + ) + .where( + and(isNotNull(pullRequests.mergedAt), gte(pullRequests.mergedAt, cutoff)), + ) + .all(); + + const byDay: Record = {}; + for (const row of rows) { + if (row.mergedAt == null) continue; + const day = new Date(row.mergedAt).toISOString().slice(0, 10); + byDay[day] = (byDay[day] ?? 0) + 1; + } + return byDay; +} diff --git a/packages/host-service/src/trpc/router/usage/history/aggregate.ts b/packages/host-service/src/trpc/router/usage/history/aggregate.ts index 09c3e57400e..034ee8274f3 100644 --- a/packages/host-service/src/trpc/router/usage/history/aggregate.ts +++ b/packages/host-service/src/trpc/router/usage/history/aggregate.ts @@ -1,11 +1,7 @@ -import { realpath } from "node:fs/promises"; -import { homedir } from "node:os"; -import { basename, join } from "node:path"; -import { discoverClaudeProfiles, discoverCodexHomes } from "../profiles"; +import { basename } from "node:path"; import type { UsageProvider } from "../types"; -import { collectLogFiles, dedupeLogFiles } from "./logs"; +import { collectUsageEntries } from "./entries"; import type { UsageLogEntry } from "./parse"; -import { parseClaudeLogFile, parseCodexLogFile } from "./parse"; import { cacheSavingsUsd, costUsd, @@ -159,7 +155,6 @@ export async function computeUsageHistory( days: number, cwdLabels: CwdLabel[] = [], ): Promise { - const home = homedir(); const labelsByLength = [...cwdLabels].sort( (a, b) => b.prefix.length - a.prefix.length, ); @@ -172,70 +167,10 @@ export async function computeUsageHistory( return start.getTime(); })(); - // Same homes the quota discovery covers: the default locations, any - // CLAUDE_CONFIG_DIR entries (comma-list), and auto-discovered profile / - // CODEX_HOME dirs — a custom config dir keeps its transcripts INSIDE the - // dir, so multi-account history means scanning every profile's projects/. - const claudeHomes = new Set([ - join(home, ".claude"), - join(home, ".config", "claude"), - ]); - for (const dir of (process.env.CLAUDE_CONFIG_DIR ?? "").split(",")) { - if (dir.trim()) claudeHomes.add(dir.trim()); - } - const [claudeProfiles, codexHomes] = await Promise.all([ - discoverClaudeProfiles(), - discoverCodexHomes(), - ]); - for (const profile of claudeProfiles) claudeHomes.add(profile.configDir); - - // Shared-history profiles symlink their projects/ into ~/.claude (see - // session-share.ts), so two homes can name the same tree under different - // paths — resolve every scan root and dedupe by real path, or the tree - // gets walked and parsed once per profile. - const resolveRoots = async (roots: string[]): Promise => { - const resolved = await Promise.all( - roots.map(async (root) => { - try { - return await realpath(root); - } catch { - return null; // Dir absent — collectLogFiles would find nothing. - } - }), - ); - return [ - ...new Set(resolved.filter((root): root is string => root !== null)), - ]; - }; - const [claudeRoots, codexRoots] = await Promise.all([ - resolveRoots([...claudeHomes].map((root) => join(root, "projects"))), - resolveRoots( - codexHomes.map((codexHome) => join(codexHome.home, "sessions")), - ), - ]); - const [claudeFileGroups, codexFileGroups] = await Promise.all([ - Promise.all(claudeRoots.map((root) => collectLogFiles(root, days + 1))), - Promise.all(codexRoots.map((root) => collectLogFiles(root, days + 1))), - ]); - const claudeFiles = dedupeLogFiles(claudeFileGroups.flat()); - const codexFiles = dedupeLogFiles(codexFileGroups.flat()); - - const entries: UsageLogEntry[] = []; - const claudeEntriesByMessage = new Map(); - const sessionLabels = new Map(); - for (const file of claudeFiles) { - await parseClaudeLogFile( - file, - claudeEntriesByMessage, - cutoffMs, - entries, - sessionLabels, - ); - } - entries.push(...claudeEntriesByMessage.values()); - for (const file of codexFiles) { - await parseCodexLogFile(file, cutoffMs, entries, sessionLabels); - } + const { entries, sessionLabels, scannedFiles } = await collectUsageEntries( + days, + cutoffMs, + ); const bucketsByDay = new Map(); const modelsByKey = new Map(); @@ -462,7 +397,7 @@ export async function computeUsageHistory( projectDetails, modelDetails, totals, - scannedFiles: claudeFiles.length + codexFiles.length, + scannedFiles: scannedFiles, pricingTableUpdated: PRICING_TABLE_UPDATED, }; } diff --git a/packages/host-service/src/trpc/router/usage/history/entries.ts b/packages/host-service/src/trpc/router/usage/history/entries.ts new file mode 100644 index 00000000000..eaf1e611f9f --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/history/entries.ts @@ -0,0 +1,93 @@ +import { realpath } from "node:fs/promises"; +import { homedir } from "node:os"; +import { join } from "node:path"; +import { discoverClaudeProfiles, discoverCodexHomes } from "../profiles"; +import { collectLogFiles, dedupeLogFiles } from "./logs"; +import type { UsageLogEntry } from "./parse"; +import { parseClaudeLogFile, parseCodexLogFile } from "./parse"; + +export interface CollectedUsage { + entries: UsageLogEntry[]; + + sessionLabels: Map; + + scannedFiles: number; +} + +export async function collectUsageEntries( + days: number, + cutoffMs: number, +): Promise { + const home = homedir(); + + // Same homes the quota discovery covers: the default locations, any + // CLAUDE_CONFIG_DIR entries (comma-list), and auto-discovered profile / + // CODEX_HOME dirs — a custom config dir keeps its transcripts INSIDE the + // dir, so multi-account history means scanning every profile's projects/. + const claudeHomes = new Set([ + join(home, ".claude"), + join(home, ".config", "claude"), + ]); + for (const dir of (process.env.CLAUDE_CONFIG_DIR ?? "").split(",")) { + if (dir.trim()) claudeHomes.add(dir.trim()); + } + const [claudeProfiles, codexHomes] = await Promise.all([ + discoverClaudeProfiles(), + discoverCodexHomes(), + ]); + for (const profile of claudeProfiles) claudeHomes.add(profile.configDir); + + // Shared-history profiles symlink their projects/ into ~/.claude (see + // session-share.ts), so two homes can name the same tree under different + // paths — resolve every scan root and dedupe by real path, or the tree + // gets walked and parsed once per profile. + const resolveRoots = async (roots: string[]): Promise => { + const resolved = await Promise.all( + roots.map(async (root) => { + try { + return await realpath(root); + } catch { + return null; // Dir absent — collectLogFiles would find nothing. + } + }), + ); + return [ + ...new Set(resolved.filter((root): root is string => root !== null)), + ]; + }; + const [claudeRoots, codexRoots] = await Promise.all([ + resolveRoots([...claudeHomes].map((root) => join(root, "projects"))), + resolveRoots( + codexHomes.map((codexHome) => join(codexHome.home, "sessions")), + ), + ]); + const [claudeFileGroups, codexFileGroups] = await Promise.all([ + Promise.all(claudeRoots.map((root) => collectLogFiles(root, days + 1))), + Promise.all(codexRoots.map((root) => collectLogFiles(root, days + 1))), + ]); + const claudeFiles = dedupeLogFiles(claudeFileGroups.flat()); + const codexFiles = dedupeLogFiles(codexFileGroups.flat()); + + const entries: UsageLogEntry[] = []; + const claudeEntriesByMessage = new Map(); + const sessionLabels = new Map(); + for (const file of claudeFiles) { + await parseClaudeLogFile( + file, + claudeEntriesByMessage, + cutoffMs, + entries, + sessionLabels, + ); + } + entries.push(...claudeEntriesByMessage.values()); + for (const file of codexFiles) { + await parseCodexLogFile(file, cutoffMs, entries, sessionLabels); + } + + return { + entries, + sessionLabels, + scannedFiles: claudeFiles.length + codexFiles.length, + }; +} diff --git a/packages/host-service/src/trpc/router/usage/history/factory-days.test.ts b/packages/host-service/src/trpc/router/usage/history/factory-days.test.ts new file mode 100644 index 00000000000..24d794780ae --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/history/factory-days.test.ts @@ -0,0 +1,114 @@ +import { describe, expect, test } from "bun:test"; +import { groupFactoryDays } from "./factory-days"; +import type { UsageLogEntry } from "./parse"; + +function entry(over: Partial = {}): UsageLogEntry { + return { + provider: "claude", + model: "claude-opus-5", + timestampMs: Date.parse("2026-08-20T12:00:00.000Z"), + cwd: "/Users/someone/secret-project", + sessionId: "session-a", + uncachedInput: 100, + cachedInput: 200, + cacheWrite5m: 50, + cacheWrite1h: 0, + output: 400, + reasoningOutput: 80, + ...over, + }; +} + +const at = (iso: string, sessionId: string) => + entry({ timestampMs: Date.parse(iso), sessionId }); + +function oneDay( + entries: UsageLogEntry[], + agentPrsByDay?: Record, +) { + const day = groupFactoryDays(entries, agentPrsByDay)[0]; + if (!day) throw new Error("expected one day"); + return day; +} + +describe("groupFactoryDays", () => { + test("counts a session once even when it switches model", () => { + const day = oneDay([ + entry({ model: "claude-opus-5", sessionId: "s1" }), + entry({ model: "claude-sonnet-5", sessionId: "s1" }), + ]); + expect(day.sessions).toBe(1); + }); + + test("sessions in the same bucket are parallel", () => { + const day = oneDay([ + at("2026-08-20T12:00:00Z", "s1"), + at("2026-08-20T12:05:00Z", "s2"), + at("2026-08-20T12:10:00Z", "s3"), + ]); + expect(day.parallelSessions).toBe(3); + }); + + test("sessions in different buckets are not parallel", () => { + const day = oneDay([ + at("2026-08-20T12:00:00Z", "s1"), + at("2026-08-20T13:00:00Z", "s2"), + at("2026-08-20T14:00:00Z", "s3"), + ]); + expect(day.sessions).toBe(3); + expect(day.parallelSessions).toBe(1); + }); + + test("takes the median across active buckets, not the peak", () => { + const day = oneDay([ + at("2026-08-20T12:00:00Z", "s1"), + at("2026-08-20T12:01:00Z", "s2"), + at("2026-08-20T12:02:00Z", "s3"), + at("2026-08-20T12:03:00Z", "s4"), + at("2026-08-20T13:00:00Z", "s5"), + at("2026-08-20T14:00:00Z", "s6"), + ]); + expect(day.parallelSessions).toBe(1); + }); + + test("an even bucket count can land on a half", () => { + const day = oneDay([ + at("2026-08-20T12:00:00Z", "s1"), + at("2026-08-20T12:01:00Z", "s2"), + at("2026-08-20T13:00:00Z", "s3"), + ]); + expect(day.parallelSessions).toBe(1.5); + }); + + test("splits on the UTC day boundary, not local", () => { + const days = groupFactoryDays([ + at("2026-08-20T23:50:00Z", "s1"), + at("2026-08-21T00:10:00Z", "s2"), + ]); + expect(days.map((d) => d.day)).toEqual(["2026-08-20", "2026-08-21"]); + }); + + test("attaches merged PR counts to their day", () => { + const day = oneDay([at("2026-08-20T12:00:00Z", "s1")], { + "2026-08-20": 4, + }); + expect(day.agentPrsMerged).toBe(4); + }); + + test("keeps a day that merged PRs but logged no usage", () => { + const days = groupFactoryDays([], { "2026-08-19": 2 }); + expect(days).toEqual([ + { + day: "2026-08-19", + sessions: 0, + parallelSessions: 0, + agentPrsMerged: 2, + }, + ]); + }); + + test("publishes no session identifiers", () => { + const days = groupFactoryDays([at("2026-08-20T12:00:00Z", "secret-id")]); + expect(JSON.stringify(days)).not.toContain("secret-id"); + }); +}); diff --git a/packages/host-service/src/trpc/router/usage/history/factory-days.ts b/packages/host-service/src/trpc/router/usage/history/factory-days.ts new file mode 100644 index 00000000000..f822d13949c --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/history/factory-days.ts @@ -0,0 +1,71 @@ +import type { UsageLogEntry } from "./parse"; + +export interface FactoryDay { + day: string; + + sessions: number; + + parallelSessions: number; + agentPrsMerged: number; +} + +const BUCKET_MS = 15 * 60_000; + +function utcDayKey(timestampMs: number): string { + return new Date(timestampMs).toISOString().slice(0, 10); +} + +function median(values: number[]): number { + if (values.length === 0) return 0; + const sorted = [...values].sort((a, b) => a - b); + const mid = sorted.length >> 1; + if (sorted.length % 2 === 1) return sorted[mid] ?? 0; + return ((sorted[mid - 1] ?? 0) + (sorted[mid] ?? 0)) / 2; +} + +interface DayBucket { + sessions: Set; + buckets: Map>; +} + +export function groupFactoryDays( + entries: UsageLogEntry[], + agentPrsByDay: Record = {}, +): FactoryDay[] { + const days = new Map(); + + for (const entry of entries) { + const day = utcDayKey(entry.timestampMs); + let bucket = days.get(day); + if (!bucket) { + bucket = { sessions: new Set(), buckets: new Map() }; + days.set(day, bucket); + } + bucket.sessions.add(entry.sessionId); + + const slot = Math.floor(entry.timestampMs / BUCKET_MS); + let slotSessions = bucket.buckets.get(slot); + if (!slotSessions) { + slotSessions = new Set(); + bucket.buckets.set(slot, slotSessions); + } + slotSessions.add(entry.sessionId); + } + + for (const day of Object.keys(agentPrsByDay)) { + if (!days.has(day)) { + days.set(day, { sessions: new Set(), buckets: new Map() }); + } + } + + return [...days.entries()] + .map(([day, bucket]) => ({ + day, + sessions: bucket.sessions.size, + parallelSessions: median( + [...bucket.buckets.values()].map((sessions) => sessions.size), + ), + agentPrsMerged: agentPrsByDay[day] ?? 0, + })) + .sort((a, b) => (a.day < b.day ? -1 : a.day > b.day ? 1 : 0)); +} diff --git a/packages/host-service/src/trpc/router/usage/history/leaderboard-days.test.ts b/packages/host-service/src/trpc/router/usage/history/leaderboard-days.test.ts new file mode 100644 index 00000000000..efa36d5e114 --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/history/leaderboard-days.test.ts @@ -0,0 +1,135 @@ +import { describe, expect, test } from "bun:test"; +import { groupEntriesByDay } from "./leaderboard-days"; +import type { UsageLogEntry } from "./parse"; + +function entry(over: Partial = {}): UsageLogEntry { + return { + provider: "claude", + model: "claude-opus-5", + timestampMs: Date.parse("2026-08-20T12:00:00.000Z"), + cwd: "/Users/someone/secret-project", + sessionId: "session-a", + uncachedInput: 100, + cachedInput: 200, + cacheWrite5m: 50, + cacheWrite1h: 0, + output: 400, + reasoningOutput: 80, + ...over, + }; +} + +describe("groupEntriesByDay", () => { + test("sums the six dimensions per day/provider/model", () => { + const [row] = groupEntriesByDay([entry(), entry()]); + expect(row).toMatchObject({ + day: "2026-08-20", + provider: "claude", + model: "claude-opus-5", + uncachedInput: 200, + cachedInput: 400, + cacheWrite5m: 100, + cacheWrite1h: 0, + output: 800, + reasoningOutput: 160, + }); + }); + + test("splits the same day across models", () => { + const rows = groupEntriesByDay([ + entry(), + entry({ model: "claude-sonnet-5" }), + ]); + expect(rows).toHaveLength(2); + expect(rows.map((r) => r.model).sort()).toEqual([ + "claude-opus-5", + "claude-sonnet-5", + ]); + }); + + test("splits the same model across providers", () => { + const rows = groupEntriesByDay([ + entry(), + entry({ provider: "codex", model: "gpt-5.6" }), + ]); + expect(rows).toHaveLength(2); + }); + + test("keys on the UTC day, not the host's local day", () => { + const late = groupEntriesByDay([ + entry({ timestampMs: Date.parse("2026-08-20T23:30:00.000Z") }), + ]); + expect(late[0]?.day).toBe("2026-08-20"); + + const early = groupEntriesByDay([ + entry({ timestampMs: Date.parse("2026-08-21T00:30:00.000Z") }), + ]); + expect(early[0]?.day).toBe("2026-08-21"); + }); + + test("counts distinct sessions, and never emits their ids", () => { + const rows = groupEntriesByDay([ + entry({ sessionId: "1f0e-aaaa" }), + entry({ sessionId: "1f0e-aaaa" }), + entry({ sessionId: "2a7b-bbbb" }), + ]); + expect(rows[0]?.sessions).toBe(2); + const serialized = JSON.stringify(rows); + expect(serialized).not.toContain("1f0e-aaaa"); + expect(serialized).not.toContain("2a7b-bbbb"); + }); + + test("carries no cwd, path or prompt into the payload", () => { + const serialized = JSON.stringify( + groupEntriesByDay([entry({ cwd: "/Users/someone/secret-project" })]), + ); + expect(serialized).not.toContain("secret-project"); + expect(serialized).not.toContain("/Users"); + }); + + test("prices via the model rate and rounds to six decimals", () => { + const [row] = groupEntriesByDay([entry()]); + expect(row?.usdEstimate).toBeGreaterThan(0); + expect( + String(row?.usdEstimate).split(".")[1]?.length ?? 0, + ).toBeLessThanOrEqual(6); + }); + + test("an unknown model taints the bucket as approximate", () => { + const [known] = groupEntriesByDay([entry()]); + expect(known?.approximate).toBe(false); + + const [unknown] = groupEntriesByDay([ + entry({ model: "claude-something-unreleased" }), + ]); + expect(unknown?.approximate).toBe(true); + }); + + test("one approximate entry taints a bucket its peers share", () => { + const rows = groupEntriesByDay([ + entry({ model: "totally-unknown" }), + entry({ model: "totally-unknown" }), + ]); + expect(rows[0]?.approximate).toBe(true); + }); + + test("returns nothing for no entries", () => { + expect(groupEntriesByDay([])).toEqual([]); + }); + + test("orders by day then model so payloads diff cleanly", () => { + const rows = groupEntriesByDay([ + entry({ timestampMs: Date.parse("2026-08-22T01:00:00.000Z") }), + entry({ + timestampMs: Date.parse("2026-08-20T01:00:00.000Z"), + model: "claude-sonnet-5", + }), + entry({ timestampMs: Date.parse("2026-08-20T01:00:00.000Z") }), + ]); + expect(rows.map((r) => `${r.day}/${r.model}`)).toEqual([ + "2026-08-20/claude-opus-5", + "2026-08-20/claude-sonnet-5", + "2026-08-22/claude-opus-5", + ]); + }); +}); diff --git a/packages/host-service/src/trpc/router/usage/history/leaderboard-days.ts b/packages/host-service/src/trpc/router/usage/history/leaderboard-days.ts new file mode 100644 index 00000000000..096f81bb47b --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/history/leaderboard-days.ts @@ -0,0 +1,116 @@ +import type { UsageProvider } from "../types"; +import { collectUsageEntries } from "./entries"; +import { type FactoryDay, groupFactoryDays } from "./factory-days"; +import type { UsageLogEntry } from "./parse"; +import { costUsd, matchModelRate, PRICING_TABLE_UPDATED } from "./pricing"; + +export interface LeaderboardDay { + day: string; + provider: UsageProvider; + model: string; + uncachedInput: number; + cachedInput: number; + cacheWrite5m: number; + cacheWrite1h: number; + output: number; + + reasoningOutput: number; + + usdEstimate: number; + + approximate: boolean; + sessions: number; +} + +export interface LeaderboardPayload { + payloadVersion: 2; + pricingTableUpdated: string; + days: LeaderboardDay[]; + + factoryDays: FactoryDay[]; +} + +function utcDayKey(timestampMs: number): string { + return new Date(timestampMs).toISOString().slice(0, 10); +} + +export function utcMidnightCutoff(days: number, now: Date): number { + const start = new Date( + Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()), + ); + start.setUTCDate(start.getUTCDate() - (days - 1)); + return start.getTime(); +} + +interface Bucket extends Omit { + sessionIds: Set; +} + +export function groupEntriesByDay(entries: UsageLogEntry[]): LeaderboardDay[] { + const buckets = new Map(); + + for (const entry of entries) { + const day = utcDayKey(entry.timestampMs); + const key = `${day}|${entry.provider}|${entry.model}`; + + let bucket = buckets.get(key); + if (!bucket) { + bucket = { + day, + provider: entry.provider, + model: entry.model, + uncachedInput: 0, + cachedInput: 0, + cacheWrite5m: 0, + cacheWrite1h: 0, + output: 0, + reasoningOutput: 0, + usdEstimate: 0, + approximate: false, + sessionIds: new Set(), + }; + buckets.set(key, bucket); + } + + const rate = matchModelRate(entry.provider, entry.model); + bucket.uncachedInput += entry.uncachedInput; + bucket.cachedInput += entry.cachedInput; + bucket.cacheWrite5m += entry.cacheWrite5m; + bucket.cacheWrite1h += entry.cacheWrite1h; + bucket.output += entry.output; + bucket.reasoningOutput += entry.reasoningOutput; + bucket.usdEstimate += costUsd(rate, entry); + + bucket.approximate ||= rate.approximate; + bucket.sessionIds.add(entry.sessionId); + } + + return [...buckets.values()] + .map(({ sessionIds, ...rest }) => ({ + ...rest, + + sessions: sessionIds.size, + usdEstimate: Number(rest.usdEstimate.toFixed(6)), + })) + .sort((a, b) => + a.day === b.day ? a.model.localeCompare(b.model) : a.day < b.day ? -1 : 1, + ); +} + +export async function computeLeaderboardPayload( + days: number, + agentPrsByDay: Record = {}, + now: Date = new Date(), +): Promise { + const { entries } = await collectUsageEntries( + days, + utcMidnightCutoff(days, now), + ); + + return { + payloadVersion: 2, + pricingTableUpdated: PRICING_TABLE_UPDATED, + days: groupEntriesByDay(entries), + factoryDays: groupFactoryDays(entries, agentPrsByDay), + }; +} diff --git a/packages/host-service/src/trpc/router/usage/usage.ts b/packages/host-service/src/trpc/router/usage/usage.ts index dd3e95ea2b3..21d1bb94766 100644 --- a/packages/host-service/src/trpc/router/usage/usage.ts +++ b/packages/host-service/src/trpc/router/usage/usage.ts @@ -5,7 +5,10 @@ import { provisionCodexProfile } from "@superset/agent-setup"; import { TRPCError } from "@trpc/server"; import { z } from "zod"; import { projects, workspaces } from "../../../db/schema"; -import { usageHistoryTask } from "../../../workers/tasks/usage"; +import { + leaderboardPayloadTask, + usageHistoryTask, +} from "../../../workers/tasks/usage"; import { protectedProcedure, queryProcedure, router } from "../../index"; import { offLoop } from "../../off-loop"; import { provisionClaudeAccount } from "./account-provisioning"; @@ -15,6 +18,7 @@ import { getDefaultAccountSelections, setDefaultAccountSelection, } from "./default-account"; +import { countAgentPrsByDay } from "./history/agent-prs"; import { removeClaudeProfile, removeCodexHome } from "./profile-remove"; import { discoverClaudeProfiles, discoverCodexHomes } from "./profiles"; import type { UsageAccount } from "./types"; @@ -308,6 +312,31 @@ export const usageRouter = router({ }), }), ), + + leaderboardPayload: queryProcedure + .meta({ timeoutMs: 120_000 }) + .input(z.object({ days: z.number().int().min(1).max(90) })) + .query( + offLoop({ + task: leaderboardPayloadTask, + prepare: ({ ctx, input }) => { + const nowMs = Date.now(); + return { + days: input.days, + nowMs, + agentPrsByDay: countAgentPrsByDay( + ctx.db, + input.days, + new Date(nowMs), + ), + }; + }, + options: ({ input }) => ({ + dedupeKey: `usage-leaderboard-payload:${input.days}`, + timeoutMs: 110_000, + }), + }), + ), }); export type { @@ -316,4 +345,8 @@ export type { UsageModelBreakdown, UsageProjectBreakdown, } from "./history/aggregate"; +export type { + LeaderboardDay, + LeaderboardPayload, +} from "./history/leaderboard-days"; export type { UsageAccount, UsageProvider, UsageQuotaWindow } from "./types"; diff --git a/packages/host-service/src/workers/tasks/usage.ts b/packages/host-service/src/workers/tasks/usage.ts index 35445a1f1be..41c8fbb0575 100644 --- a/packages/host-service/src/workers/tasks/usage.ts +++ b/packages/host-service/src/workers/tasks/usage.ts @@ -7,6 +7,8 @@ import type { UsageHistory, } from "../../trpc/router/usage/history/aggregate.ts"; import { computeUsageHistory } from "../../trpc/router/usage/history/aggregate.ts"; +import type { LeaderboardPayload } from "../../trpc/router/usage/history/leaderboard-days.ts"; +import { computeLeaderboardPayload } from "../../trpc/router/usage/history/leaderboard-days.ts"; import { defineWorkerTask } from "../define-worker-task.ts"; export const usageHistoryTask = defineWorkerTask< @@ -17,4 +19,13 @@ export const usageHistoryTask = defineWorkerTask< handler: ({ days, cwdLabels }) => computeUsageHistory(days, cwdLabels), }); -export const usageTasks = [usageHistoryTask]; +export const leaderboardPayloadTask = defineWorkerTask< + { days: number; nowMs: number; agentPrsByDay: Record }, + LeaderboardPayload +>({ + type: "usage/leaderboard-payload", + handler: ({ days, nowMs, agentPrsByDay }) => + computeLeaderboardPayload(days, agentPrsByDay, new Date(nowMs)), +}); + +export const usageTasks = [usageHistoryTask, leaderboardPayloadTask]; diff --git a/packages/shared/package.json b/packages/shared/package.json index 4d7dab2d6a9..801ed84eb76 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -16,6 +16,14 @@ "types": "./src/constants.ts", "default": "./src/constants.ts" }, + "./format-scaled": { + "types": "./src/format-scaled.ts", + "default": "./src/format-scaled.ts" + }, + "./format-tokens": { + "types": "./src/format-tokens.ts", + "default": "./src/format-tokens.ts" + }, "./git-hook-tolerance": { "types": "./src/git-hook-tolerance.ts", "default": "./src/git-hook-tolerance.ts" diff --git a/packages/shared/src/format-scaled.ts b/packages/shared/src/format-scaled.ts new file mode 100644 index 00000000000..5dff9cd194a --- /dev/null +++ b/packages/shared/src/format-scaled.ts @@ -0,0 +1,28 @@ +export interface ScaleUnit { + limit: number; + suffix: string; + digits: number; +} + +/** + * Renders a value against the largest unit it clears, then re-checks the + * rounded result: rounding can carry a value into the next unit, so 999,999 + * must read 1.0M rather than 1000K. + * + * Only carries between suffixed units. A value below the smallest unit is + * handed to `base` as-is, so a formatter with decimals can still render e.g. + * 999.999 as "1000.00" — unscaled, but not misleading the way "1000K" is. + */ +export function formatScaled( + value: number, + units: readonly ScaleUnit[], + base: (value: number) => string, +): string { + for (const [index, unit] of units.entries()) { + if (value < unit.limit) continue; + const carried = Number((value / unit.limit).toFixed(unit.digits)) >= 1000; + const target = (carried ? units[index - 1] : undefined) ?? unit; + return `${(value / target.limit).toFixed(target.digits)}${target.suffix}`; + } + return base(value); +} diff --git a/packages/shared/src/format-tokens.test.ts b/packages/shared/src/format-tokens.test.ts new file mode 100644 index 00000000000..1755cd28daa --- /dev/null +++ b/packages/shared/src/format-tokens.test.ts @@ -0,0 +1,50 @@ +import { describe, expect, it } from "bun:test"; +import { formatScaled } from "./format-scaled"; +import { formatTokens } from "./format-tokens"; + +describe("formatTokens", () => { + it("scales through K/M/B/T", () => { + expect(formatTokens(1_240_000_000_000)).toBe("1.24T"); + expect(formatTokens(13_930_000_000)).toBe("13.9B"); + expect(formatTokens(4_200_000)).toBe("4.2M"); + expect(formatTokens(850_000)).toBe("850K"); + expect(formatTokens(312)).toBe("312"); + }); + + it("groups raw counts under a thousand", () => { + expect(formatTokens(0)).toBe("0"); + expect(formatTokens(999)).toBe("999"); + }); + + it("promotes values that round up into the next unit", () => { + expect(formatTokens(999_999)).toBe("1.0M"); + expect(formatTokens(999_999_999)).toBe("1.0B"); + expect(formatTokens(999_999_999_999)).toBe("1.00T"); + }); + + it("keeps values that stay inside their unit", () => { + expect(formatTokens(1_000)).toBe("1K"); + expect(formatTokens(999_400)).toBe("999K"); + expect(formatTokens(1_000_000)).toBe("1.0M"); + expect(formatTokens(1_000_000_000)).toBe("1.0B"); + }); +}); + +describe("formatScaled", () => { + const units = [ + { limit: 1e6, suffix: "M", digits: 1 }, + { limit: 1e3, suffix: "K", digits: 1 }, + ]; + + it("carries a rounded value into the next unit", () => { + expect(formatScaled(999_999, units, String)).toBe("1.0M"); + }); + + it("has no unit above the largest to carry into", () => { + expect(formatScaled(999_999_999, units, String)).toBe("1000.0M"); + }); + + it("hands values below the smallest unit to the base formatter", () => { + expect(formatScaled(999, units, (v) => v.toFixed(2))).toBe("999.00"); + }); +}); diff --git a/packages/shared/src/format-tokens.ts b/packages/shared/src/format-tokens.ts new file mode 100644 index 00000000000..83fc3f2f20f --- /dev/null +++ b/packages/shared/src/format-tokens.ts @@ -0,0 +1,15 @@ +import { formatScaled, type ScaleUnit } from "./format-scaled"; + +const UNITS: readonly ScaleUnit[] = [ + { limit: 1e12, suffix: "T", digits: 2 }, + { limit: 1e9, suffix: "B", digits: 1 }, + { limit: 1e6, suffix: "M", digits: 1 }, + { limit: 1e3, suffix: "K", digits: 0 }, +]; + +/** "1.24T", "13.9B", "4.2M", "850K", "312" */ +export function formatTokens(tokens: number): string { + return formatScaled(tokens, UNITS, (value) => + Math.round(value).toLocaleString("en-US"), + ); +} diff --git a/packages/trpc/package.json b/packages/trpc/package.json index 8a60fc412e3..fb0bb4ab771 100644 --- a/packages/trpc/package.json +++ b/packages/trpc/package.json @@ -12,6 +12,22 @@ "types": "./src/router/page/schema.ts", "default": "./src/router/page/schema.ts" }, + "./leaderboard-queries": { + "types": "./src/router/leaderboard/queries.ts", + "default": "./src/router/leaderboard/queries.ts" + }, + "./leaderboard-schema": { + "types": "./src/router/leaderboard/schema.ts", + "default": "./src/router/leaderboard/schema.ts" + }, + "./leaderboard-periods": { + "types": "./src/router/leaderboard/periods.ts", + "default": "./src/router/leaderboard/periods.ts" + }, + "./leaderboard-types": { + "types": "./src/router/leaderboard/types.ts", + "default": "./src/router/leaderboard/types.ts" + }, "./integrations/*": { "types": "./src/lib/integrations/*/index.ts", "default": "./src/lib/integrations/*/index.ts" diff --git a/packages/trpc/src/root.ts b/packages/trpc/src/root.ts index 259530ee2b8..ebcd1776446 100644 --- a/packages/trpc/src/root.ts +++ b/packages/trpc/src/root.ts @@ -10,6 +10,7 @@ import { chatRouter } from "./router/chat"; import { cloudWorkspaceRouter } from "./router/cloud-workspace"; import { hostRouter } from "./router/host"; import { integrationRouter } from "./router/integration"; +import { leaderboardRouter } from "./router/leaderboard"; import { organizationRouter } from "./router/organization"; import { pageRouter } from "./router/page"; import { pageCommentRouter } from "./router/page-comment"; @@ -33,6 +34,7 @@ export const appRouter = createTRPCRouter({ cloudWorkspace: cloudWorkspaceRouter, host: hostRouter, integration: integrationRouter, + leaderboard: leaderboardRouter, organization: organizationRouter, page: pageRouter, pageComment: pageCommentRouter, diff --git a/packages/trpc/src/router/leaderboard/index.ts b/packages/trpc/src/router/leaderboard/index.ts new file mode 100644 index 00000000000..fb44fcfde96 --- /dev/null +++ b/packages/trpc/src/router/leaderboard/index.ts @@ -0,0 +1 @@ +export { leaderboardRouter } from "./leaderboard"; diff --git a/packages/trpc/src/router/leaderboard/leaderboard.ts b/packages/trpc/src/router/leaderboard/leaderboard.ts new file mode 100644 index 00000000000..4470feada2a --- /dev/null +++ b/packages/trpc/src/router/leaderboard/leaderboard.ts @@ -0,0 +1,713 @@ +import { db, dbWs } from "@superset/db/client"; +import { + leaderboardDaily, + leaderboardDailyFactory, + leaderboardParticipants, + userIdentities, + users, +} from "@superset/db/schema"; +import { TRPCError } from "@trpc/server"; +import { Ratelimit } from "@upstash/ratelimit"; +import { Redis } from "@upstash/redis"; +import { and, eq, gte, lte, sql } from "drizzle-orm"; +import { env } from "../../env"; +import { + createTRPCRouter, + protectedProcedure, + publicProcedure, +} from "../../trpc"; +import { requireActiveOrgMembership } from "../utils/active-org"; +import { isUniqueViolation } from "../utils/unique-violation"; +import { type LeaderboardPeriod, resolveDayRange } from "./periods"; +import { getParticipant, getStandings, getStats } from "./queries"; +import { + joinSchema, + MAX_HOSTS_PER_USER, + meSchema, + PUBLISH_WINDOW_DAYS, + participantSchema, + previewRankSchema, + publishSchema, + standingsSchema, + windowSchema, +} from "./schema"; +import { computeTier, type FactoryDayRow, type Tier } from "./tier"; + +const redis = + env.KV_REST_API_URL && env.KV_REST_API_TOKEN + ? new Redis({ url: env.KV_REST_API_URL, token: env.KV_REST_API_TOKEN }) + : null; + +const publishRateLimit = redis + ? new Ratelimit({ + redis, + limiter: Ratelimit.slidingWindow(30, "1 h"), + prefix: "ratelimit:leaderboard:publish", + }) + : null; + +const publicReadRateLimit = redis + ? new Ratelimit({ + redis, + limiter: Ratelimit.slidingWindow(60, "1 m"), + prefix: "ratelimit:leaderboard:public", + }) + : null; + +const joinRateLimit = redis + ? new Ratelimit({ + redis, + limiter: Ratelimit.slidingWindow(10, "1 h"), + prefix: "ratelimit:leaderboard:join", + }) + : null; + +const previewRateLimit = redis + ? new Ratelimit({ + redis, + limiter: Ratelimit.slidingWindow(30, "1 h"), + prefix: "ratelimit:leaderboard:preview", + }) + : null; + +/** + * Write path: fail closed. A limiter outage becomes a clean retryable signal + * rather than an unhandled 500. Anonymous reads use `enforceOpen` instead. + */ +async function enforce( + limiter: Ratelimit | null, + key: string, + message: string, +): Promise { + if (!limiter) return; + let success: boolean; + try { + ({ success } = await limiter.limit(key)); + } catch (error) { + console.error("[leaderboard] rate limiter unavailable:", error); + throw new TRPCError({ code: "SERVICE_UNAVAILABLE", message }); + } + if (!success) { + throw new TRPCError({ code: "TOO_MANY_REQUESTS", message }); + } +} + +type Tx = Parameters[0]>[0]; + +/** + * Both daily tables carry hostId, so counting one lets a factory-only payload + * mint hosts freely. The participant row is locked first so concurrent + * publishes cannot each observe a count below the cap and all write. + */ +async function enforceHostBudget( + tx: Tx, + userId: string, + hostId: string, +): Promise { + await tx.execute( + sql`select 1 from leaderboard_participants where user_id = ${userId} for update`, + ); + + const seen = await tx.execute<{ hosts: number }>(sql` + select count(*)::int as hosts from ( + select host_id from leaderboard_daily + where user_id = ${userId} and host_id <> ${hostId} + union + select host_id from leaderboard_daily_factory + where user_id = ${userId} and host_id <> ${hostId} + ) hosts + `); + + if (Number(seen.rows[0]?.hosts ?? 0) >= MAX_HOSTS_PER_USER) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: "Too many machines publishing for this account.", + }); + } +} + +const DAY_MS = 24 * 60 * 60 * 1000; + +function utcDayKey(ms: number): string { + return new Date(ms).toISOString().slice(0, 10); +} + +/** + * Day keys are client-asserted, so an unbounded value would pollute + * dayRangeStart/End and all-time totals — and a future-dated row would + * pre-load tomorrow's board. One day of forward slack absorbs host/server + * clock skew across a UTC midnight. + */ +function assertDaysInWindow(days: readonly { day: string }[]): void { + if (days.length === 0) return; + const now = Date.now(); + const oldest = utcDayKey(now - PUBLISH_WINDOW_DAYS * DAY_MS); + const newest = utcDayKey(now + DAY_MS); + + for (const { day } of days) { + if (day < oldest || day > newest) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: `Day ${day} is outside the publishable window.`, + }); + } + } +} + +async function enforcePublicRead(headers: Headers): Promise { + if (!publicReadRateLimit) return; + const ip = + headers.get("x-forwarded-for")?.split(",")[0]?.trim() || + headers.get("x-real-ip") || + "unknown"; + + let success: boolean; + try { + ({ success } = await publicReadRateLimit.limit(ip)); + } catch (error) { + // Fail open: these are CDN-cached anonymous reads, and a Redis blip + // should not blank the public board. + console.error("[leaderboard] public rate limiter unavailable:", error); + return; + } + if (!success) { + throw new TRPCError({ + code: "TOO_MANY_REQUESTS", + message: "Rate limit exceeded.", + }); + } +} + +function slugHandle(raw: string): string | null { + const slug = raw + .trim() + .toLowerCase() + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-+|-+$/g, "") + .slice(0, 39) + .replace(/-+$/g, ""); + return slug.length >= 2 ? slug : null; +} + +const HANDLE_CONSTRAINT = "leaderboard_participants_handle_unique"; + +async function requireParticipant(userId: string) { + const [row] = await db + .select() + .from(leaderboardParticipants) + .where(eq(leaderboardParticipants.userId, userId)) + .limit(1); + + if (!row || row.revokedAt) { + throw new TRPCError({ + code: "PRECONDITION_FAILED", + message: "Not on the leaderboard. Opt in first.", + }); + } + return row; +} + +/** + * Assigns straight from the aggregate in SQL. Round-tripping the bigint sums + * through a JS number silently loses precision past 2^53, which would corrupt + * all-time standings rather than fail loudly. + */ +async function recomputeTotals(userId: string): Promise { + await db.execute(sql` + update leaderboard_participants p set + tokens = t.tokens, + usd = t.usd, + sessions = t.sessions, + uncached_input = t.uncached_input, + cached_input = t.cached_input, + cache_write_5m = t.cache_write_5m, + cache_write_1h = t.cache_write_1h, + output = t.output, + reasoning_output = t.reasoning_output, + approximate = t.approximate, + day_range_start = t.day_range_start, + day_range_end = t.day_range_end, + last_published_at = now() + from ( + select + coalesce(sum(d.tokens), 0)::bigint as tokens, + coalesce(sum(d.usd_estimate), 0) as usd, + coalesce(sum(d.sessions), 0)::int as sessions, + coalesce(sum(d.uncached_input), 0)::bigint as uncached_input, + coalesce(sum(d.cached_input), 0)::bigint as cached_input, + coalesce(sum(d.cache_write_5m), 0)::bigint as cache_write_5m, + coalesce(sum(d.cache_write_1h), 0)::bigint as cache_write_1h, + coalesce(sum(d.output), 0)::bigint as output, + coalesce(sum(d.reasoning_output), 0)::bigint as reasoning_output, + coalesce(bool_or(d.approximate), false) as approximate, + min(d.day) as day_range_start, + max(d.day) as day_range_end + from leaderboard_daily d + where d.user_id = ${userId} + ) t + where p.user_id = ${userId} + `); +} + +const TIER_WINDOW_DAYS = 30; + +function tierWindowStart(now: Date = new Date()): string { + const start = new Date(now); + start.setUTCDate(start.getUTCDate() - (TIER_WINDOW_DAYS - 1)); + return start.toISOString().slice(0, 10); +} + +async function recomputeTier(userId: string): Promise { + const from = tierWindowStart(); + + const [factoryRows, tokenRows, current] = await Promise.all([ + db + .select({ + day: leaderboardDailyFactory.day, + sessions: sql`coalesce(sum(${leaderboardDailyFactory.sessions}), 0)::int`, + parallelSessions: sql`coalesce(max(${leaderboardDailyFactory.parallelSessions}), 0)`, + agentPrsMerged: sql`coalesce(max(${leaderboardDailyFactory.agentPrsMerged}), 0)::int`, + }) + .from(leaderboardDailyFactory) + .where( + and( + eq(leaderboardDailyFactory.userId, userId), + gte(leaderboardDailyFactory.day, from), + ), + ) + .groupBy(leaderboardDailyFactory.day), + db + .select({ + day: leaderboardDaily.day, + tokens: sql`coalesce(sum(${leaderboardDaily.tokens}), 0)::bigint`, + }) + .from(leaderboardDaily) + .where( + and( + eq(leaderboardDaily.userId, userId), + gte(leaderboardDaily.day, from), + ), + ) + .groupBy(leaderboardDaily.day), + db + .select({ tier: leaderboardParticipants.tier }) + .from(leaderboardParticipants) + .where(eq(leaderboardParticipants.userId, userId)) + .limit(1), + ]); + + const tokensByDay = new Map( + tokenRows.map((row) => [row.day, Number(row.tokens)]), + ); + + const rows: FactoryDayRow[] = factoryRows.map((row) => ({ + day: row.day, + tokens: tokensByDay.get(row.day) ?? 0, + sessions: Number(row.sessions), + parallelSessions: Number(row.parallelSessions), + agentPrsMerged: Number(row.agentPrsMerged), + })); + + const result = computeTier(rows, (current[0]?.tier ?? 0) as Tier); + + await db + .update(leaderboardParticipants) + .set({ + tier: result.tier, + tierComputedAt: new Date(), + activeDays: result.activeDays, + axisWidth: result.axisWidth.toFixed(2), + axisDepth: result.axisDepth, + axisOutput: result.axisOutput.toFixed(2), + }) + .where(eq(leaderboardParticipants.userId, userId)); +} + +async function rankFor( + period: LeaderboardPeriod, + periodStart: string | undefined, + tokens: number, + excludeUserId: string | null, +): Promise<{ rank: number; total: number }> { + const range = resolveDayRange(period, periodStart); + const exclude = excludeUserId + ? sql`and p.user_id <> ${excludeUserId}` + : sql``; + const eligible = sql`p.visibility = 'public' and p.revoked_at is null and p.flagged_at is null and u.deleted_at is null ${exclude}`; + + if (!range) { + const rows = await db.execute<{ ahead: number; total: number }>(sql` + select + count(*) filter (where p.tokens > ${tokens})::int as ahead, + count(*)::int as total + from leaderboard_participants p + join auth.users u on u.id = p.user_id + where ${eligible} and p.tokens > 0 + `); + const row = rows.rows[0]; + return { + rank: Number(row?.ahead ?? 0) + 1, + total: Number(row?.total ?? 0), + }; + } + + const rows = await db.execute<{ ahead: number; total: number }>(sql` + with totals as ( + select d.user_id, sum(d.tokens) as tokens + from leaderboard_daily d + join leaderboard_participants p on p.user_id = d.user_id + join auth.users u on u.id = p.user_id + where d.day between ${range.from} and ${range.to} and ${eligible} + group by d.user_id + ) + select + count(*) filter (where tokens > ${tokens})::int as ahead, + count(*)::int as total + from totals + `); + const row = rows.rows[0]; + return { rank: Number(row?.ahead ?? 0) + 1, total: Number(row?.total ?? 0) }; +} + +export const leaderboardRouter = createTRPCRouter({ + join: protectedProcedure + .input(joinSchema) + .mutation(async ({ ctx, input }) => { + const userId = ctx.session.user.id; + + await enforce( + joinRateLimit, + userId, + "Too many attempts. Try again later.", + ); + + const [taken] = await db + .select({ userId: leaderboardParticipants.userId }) + .from(leaderboardParticipants) + .where(eq(leaderboardParticipants.handle, input.handle)) + .limit(1); + + if (taken && taken.userId !== userId) { + throw new TRPCError({ + code: "CONFLICT", + message: "That handle is taken.", + }); + } + + const organizationId = await requireActiveOrgMembership(ctx); + + try { + const [row] = await db + .insert(leaderboardParticipants) + .values({ + userId, + handle: input.handle, + visibility: input.visibility, + organizationId, + }) + .onConflictDoUpdate({ + target: leaderboardParticipants.userId, + set: { + handle: input.handle, + visibility: input.visibility, + organizationId, + optedInAt: new Date(), + }, + }) + .returning(); + + return row; + } catch (error) { + if (isUniqueViolation(error, HANDLE_CONSTRAINT)) { + throw new TRPCError({ + code: "CONFLICT", + message: "That handle is taken.", + }); + } + throw error; + } + }), + + suggestedHandle: protectedProcedure.query(async ({ ctx }) => { + const userId = ctx.session.user.id; + + const [identity] = await db + .select({ handle: userIdentities.handle }) + .from(userIdentities) + .where( + and( + eq(userIdentities.userId, userId), + eq(userIdentities.provider, "github"), + ), + ) + .limit(1); + + const [account] = await db + .select({ name: users.name, email: users.email }) + .from(users) + .where(eq(users.id, userId)) + .limit(1); + + const candidate = + identity?.handle ?? + account?.name ?? + account?.email?.split("@")[0] ?? + null; + const suggestion = candidate ? slugHandle(candidate) : null; + if (!suggestion) return { handle: null, taken: false, source: null }; + + const [clash] = await db + .select({ userId: leaderboardParticipants.userId }) + .from(leaderboardParticipants) + .where(eq(leaderboardParticipants.handle, suggestion)) + .limit(1); + + return { + handle: suggestion, + taken: Boolean(clash && clash.userId !== userId), + source: identity?.handle ? ("github" as const) : ("account" as const), + }; + }), + + setVisibility: protectedProcedure + .input(joinSchema.pick({ visibility: true })) + .mutation(async ({ ctx, input }) => { + await requireParticipant(ctx.session.user.id); + await db + .update(leaderboardParticipants) + .set({ visibility: input.visibility }) + .where(eq(leaderboardParticipants.userId, ctx.session.user.id)); + return { success: true }; + }), + + leave: protectedProcedure.mutation(async ({ ctx }) => { + const userId = ctx.session.user.id; + await dbWs.transaction(async (tx) => { + await tx + .delete(leaderboardDaily) + .where(eq(leaderboardDaily.userId, userId)); + await tx + .delete(leaderboardDailyFactory) + .where(eq(leaderboardDailyFactory.userId, userId)); + await tx + .delete(leaderboardParticipants) + .where(eq(leaderboardParticipants.userId, userId)); + }); + return { success: true }; + }), + + publish: protectedProcedure + .input(publishSchema) + .mutation(async ({ ctx, input }) => { + const userId = ctx.session.user.id; + await enforce( + publishRateLimit, + userId, + "Too many publishes. Try again later.", + ); + await requireParticipant(userId); + + if (input.days.length === 0 && input.factoryDays.length === 0) { + return { written: 0, days: 0 }; + } + + assertDaysInWindow(input.days); + assertDaysInWindow(input.factoryDays); + const rows = input.days.map((day) => ({ + userId, + day: day.day, + provider: day.provider, + model: day.model, + hostId: input.hostId, + uncachedInput: day.uncachedInput, + cachedInput: day.cachedInput, + cacheWrite5m: day.cacheWrite5m, + cacheWrite1h: day.cacheWrite1h, + output: day.output, + reasoningOutput: day.reasoningOutput, + + tokens: + day.uncachedInput + + day.cachedInput + + day.cacheWrite5m + + day.cacheWrite1h + + day.output, + usdEstimate: day.usdEstimate.toFixed(6), + approximate: day.approximate, + sessions: day.sessions, + })); + + await dbWs.transaction(async (tx) => { + await enforceHostBudget(tx, userId, input.hostId); + + if (rows.length > 0) { + await tx + .insert(leaderboardDaily) + .values(rows) + .onConflictDoUpdate({ + target: [ + leaderboardDaily.userId, + leaderboardDaily.day, + leaderboardDaily.provider, + leaderboardDaily.model, + leaderboardDaily.hostId, + ], + set: { + uncachedInput: sql`excluded.uncached_input`, + cachedInput: sql`excluded.cached_input`, + cacheWrite5m: sql`excluded.cache_write_5m`, + cacheWrite1h: sql`excluded.cache_write_1h`, + output: sql`excluded.output`, + reasoningOutput: sql`excluded.reasoning_output`, + tokens: sql`excluded.tokens`, + usdEstimate: sql`excluded.usd_estimate`, + approximate: sql`excluded.approximate`, + sessions: sql`excluded.sessions`, + updatedAt: new Date(), + }, + }); + } + + if (input.factoryDays.length > 0) { + await tx + .insert(leaderboardDailyFactory) + .values( + input.factoryDays.map((day) => ({ + userId, + day: day.day, + hostId: input.hostId, + sessions: day.sessions, + parallelSessions: day.parallelSessions.toFixed(2), + agentPrsMerged: day.agentPrsMerged, + })), + ) + .onConflictDoUpdate({ + target: [ + leaderboardDailyFactory.userId, + leaderboardDailyFactory.day, + leaderboardDailyFactory.hostId, + ], + set: { + sessions: sql`excluded.sessions`, + parallelSessions: sql`excluded.parallel_sessions`, + agentPrsMerged: sql`excluded.agent_prs_merged`, + updatedAt: new Date(), + }, + }); + } + }); + + await recomputeTotals(userId); + await recomputeTier(userId); + const distinctDays = new Set([ + ...input.days.map((day) => day.day), + ...input.factoryDays.map((day) => day.day), + ]).size; + return { written: rows.length, days: distinctDays }; + }), + + standings: protectedProcedure + .input(standingsSchema) + .query(async ({ input }) => await getStandings(input)), + + public: createTRPCRouter({ + standings: publicProcedure + .input(standingsSchema) + .query(async ({ ctx, input }) => { + await enforcePublicRead(ctx.headers); + return await getStandings(input); + }), + + stats: publicProcedure.input(windowSchema).query(async ({ ctx, input }) => { + await enforcePublicRead(ctx.headers); + return await getStats(input); + }), + + participant: publicProcedure + .input(participantSchema) + .query(async ({ ctx, input }) => { + await enforcePublicRead(ctx.headers); + const profile = await getParticipant(input.handle, input); + if (!profile) { + throw new TRPCError({ code: "NOT_FOUND", message: "Not found" }); + } + return profile; + }), + }), + + previewRank: protectedProcedure + .input(previewRankSchema) + .query(async ({ ctx, input }) => { + await enforce( + previewRateLimit, + ctx.session.user.id, + "Too many rank previews. Try again later.", + ); + + const { rank, total } = await rankFor( + input.period, + input.periodStart, + input.tokens, + ctx.session.user.id, + ); + + return { + rank, + + total: total + 1, + percentile: + total > 0 ? Math.round((1 - (rank - 1) / total) * 100) : null, + }; + }), + + me: protectedProcedure.input(meSchema).query(async ({ ctx, input }) => { + const userId = ctx.session.user.id; + const [row] = await db + .select() + .from(leaderboardParticipants) + .where(eq(leaderboardParticipants.userId, userId)) + .limit(1); + + if (!row || row.revokedAt) return null; + + const range = resolveDayRange(input.period, input.periodStart); + let tokens = row.tokens; + + if (range) { + const [agg] = await db + .select({ + tokens: sql`coalesce(sum(${leaderboardDaily.tokens}), 0)::bigint`, + }) + .from(leaderboardDaily) + .where( + and( + eq(leaderboardDaily.userId, userId), + gte(leaderboardDaily.day, range.from), + lte(leaderboardDaily.day, range.to), + ), + ); + tokens = Number(agg?.tokens ?? 0); + } + + const { rank, total } = await rankFor( + input.period, + input.periodStart, + tokens, + userId, + ); + + return { + handle: row.handle, + visibility: row.visibility, + lastPublishedAt: row.lastPublishedAt, + period: input.period, + range, + tokens, + usd: row.usd, + sessions: row.sessions, + approximate: row.approximate, + rank, + total: total + 1, + }; + }), +}); diff --git a/packages/trpc/src/router/leaderboard/periods.test.ts b/packages/trpc/src/router/leaderboard/periods.test.ts new file mode 100644 index 00000000000..6eab8e87691 --- /dev/null +++ b/packages/trpc/src/router/leaderboard/periods.test.ts @@ -0,0 +1,158 @@ +import { describe, expect, test } from "bun:test"; +import { resolveDayRange, resolveWindow } from "./periods"; + +const THURSDAY = new Date("2026-08-20T12:00:00.000Z"); + +describe("resolveDayRange", () => { + test("all-time has no range, so callers read the rolled-up totals", () => { + expect(resolveDayRange("all", undefined, THURSDAY)).toBeNull(); + }); + + test("day is a single inclusive key", () => { + expect(resolveDayRange("day", undefined, THURSDAY)).toEqual({ + from: "2026-08-20", + to: "2026-08-20", + }); + }); + + test("week runs Monday to Sunday, not Sunday to Saturday", () => { + expect(resolveDayRange("week", undefined, THURSDAY)).toEqual({ + from: "2026-08-17", + to: "2026-08-23", + }); + }); + + test("a Monday anchor is the start of its own week, not the previous one", () => { + expect(resolveDayRange("week", "2026-08-17", THURSDAY)).toEqual({ + from: "2026-08-17", + to: "2026-08-23", + }); + }); + + test("a Sunday anchor belongs to the week that began six days earlier", () => { + expect(resolveDayRange("week", "2026-08-23", THURSDAY)).toEqual({ + from: "2026-08-17", + to: "2026-08-23", + }); + }); + + test("week spanning a month boundary keeps both months", () => { + expect(resolveDayRange("week", "2026-09-01", THURSDAY)).toEqual({ + from: "2026-08-31", + to: "2026-09-06", + }); + }); + + test("month covers the calendar month containing the anchor", () => { + expect(resolveDayRange("month", undefined, THURSDAY)).toEqual({ + from: "2026-08-01", + to: "2026-08-31", + }); + }); + + test("month handles 30-day months", () => { + expect(resolveDayRange("month", "2026-09-15", THURSDAY)).toEqual({ + from: "2026-09-01", + to: "2026-09-30", + }); + }); + + test("month handles a leap February", () => { + expect(resolveDayRange("month", "2028-02-10", THURSDAY)).toEqual({ + from: "2028-02-01", + to: "2028-02-29", + }); + }); + + test("anchors are interpreted as UTC midnight, never local", () => { + expect(resolveDayRange("day", "2026-08-20", THURSDAY)).toEqual({ + from: "2026-08-20", + to: "2026-08-20", + }); + }); + + test("rejects a malformed anchor rather than silently using today", () => { + expect(() => resolveDayRange("day", "not-a-date", THURSDAY)).toThrow(); + }); +}); + +describe("rolling windows", () => { + test("7d ends on the anchor and spans seven days inclusive", () => { + expect(resolveDayRange("7d", undefined, THURSDAY)).toEqual({ + from: "2026-08-14", + to: "2026-08-20", + }); + }); + + test("30d spans thirty days inclusive", () => { + expect(resolveDayRange("30d", undefined, THURSDAY)).toEqual({ + from: "2026-07-22", + to: "2026-08-20", + }); + }); + + test("rolling windows cross month boundaries without truncating", () => { + expect(resolveDayRange("7d", "2026-09-03", THURSDAY)).toEqual({ + from: "2026-08-28", + to: "2026-09-03", + }); + }); +}); + +describe("resolveWindow", () => { + test("an explicit range beats the named period", () => { + expect( + resolveWindow({ + period: "month", + from: "2026-01-05", + to: "2026-01-09", + now: THURSDAY, + }), + ).toEqual({ from: "2026-01-05", to: "2026-01-09" }); + }); + + test("a backwards range is normalised rather than returning nothing", () => { + expect( + resolveWindow({ + period: "month", + from: "2026-01-09", + to: "2026-01-05", + now: THURSDAY, + }), + ).toEqual({ from: "2026-01-05", to: "2026-01-09" }); + }); + + test("a half-specified range falls back to the period", () => { + expect( + resolveWindow({ period: "day", from: "2026-01-09", now: THURSDAY }), + ).toEqual({ from: "2026-08-20", to: "2026-08-20" }); + }); + + test("all-time stays rangeless even alongside a period start", () => { + expect( + resolveWindow({ + period: "all", + periodStart: "2026-01-01", + now: THURSDAY, + }), + ).toBeNull(); + }); + + test("caps an oversized explicit range at MAX_WINDOW_DAYS", () => { + expect( + resolveWindow({ period: "all", from: "1900-01-01", to: "2026-08-25" }), + ).toEqual({ from: "2025-08-25", to: "2026-08-25" }); + }); + + test("leaves a range inside the cap untouched", () => { + expect( + resolveWindow({ period: "all", from: "2026-08-01", to: "2026-08-25" }), + ).toEqual({ from: "2026-08-01", to: "2026-08-25" }); + }); + + test("caps a reversed oversized range after ordering it", () => { + expect( + resolveWindow({ period: "all", from: "2026-08-25", to: "1900-01-01" }), + ).toEqual({ from: "2025-08-25", to: "2026-08-25" }); + }); +}); diff --git a/packages/trpc/src/router/leaderboard/periods.ts b/packages/trpc/src/router/leaderboard/periods.ts new file mode 100644 index 00000000000..df6c5b66073 --- /dev/null +++ b/packages/trpc/src/router/leaderboard/periods.ts @@ -0,0 +1,112 @@ +export const LEADERBOARD_PERIODS = [ + "day", + "7d", + "30d", + "week", + "month", + "all", +] as const; +export type LeaderboardPeriod = (typeof LEADERBOARD_PERIODS)[number]; + +const DAY_KEY = /^\d{4}-\d{2}-\d{2}$/; + +export function isDayKey(value: string): boolean { + if (!DAY_KEY.test(value)) return false; + const parsed = new Date(`${value}T00:00:00.000Z`); + return ( + !Number.isNaN(parsed.getTime()) && + parsed.toISOString().slice(0, 10) === value + ); +} + +export const MAX_WINDOW_DAYS = 366; + +export interface DayRange { + from: string; + + to: string; +} + +function toDayKey(date: Date): string { + return date.toISOString().slice(0, 10); +} + +function parseDayKey(day: string): Date { + return new Date(`${day}T00:00:00.000Z`); +} + +function startOfWeek(date: Date): Date { + const start = new Date(date); + const weekday = (start.getUTCDay() + 6) % 7; + start.setUTCDate(start.getUTCDate() - weekday); + return start; +} + +function addDays(date: Date, days: number): Date { + const next = new Date(date); + next.setUTCDate(next.getUTCDate() + days); + return next; +} + +export function resolveDayRange( + period: LeaderboardPeriod, + periodStart?: string, + now: Date = new Date(), +): DayRange | null { + if (period === "all") return null; + + const anchor = periodStart ? parseDayKey(periodStart) : now; + if (Number.isNaN(anchor.getTime())) { + throw new Error(`Invalid periodStart: ${periodStart}`); + } + + if (period === "day") { + const day = toDayKey(anchor); + return { from: day, to: day }; + } + + if (period === "7d" || period === "30d") { + const span = period === "7d" ? 7 : 30; + return { + from: toDayKey(addDays(anchor, -(span - 1))), + to: toDayKey(anchor), + }; + } + + if (period === "week") { + const start = startOfWeek(anchor); + return { from: toDayKey(start), to: toDayKey(addDays(start, 6)) }; + } + + const start = new Date( + Date.UTC(anchor.getUTCFullYear(), anchor.getUTCMonth(), 1), + ); + const end = new Date( + Date.UTC(anchor.getUTCFullYear(), anchor.getUTCMonth() + 1, 0), + ); + return { from: toDayKey(start), to: toDayKey(end) }; +} + +function clampSpan(range: DayRange): DayRange { + const earliest = toDayKey( + addDays(parseDayKey(range.to), -(MAX_WINDOW_DAYS - 1)), + ); + return range.from < earliest ? { from: earliest, to: range.to } : range; +} + +export function resolveWindow(opts: { + period: LeaderboardPeriod; + periodStart?: string; + from?: string; + to?: string; + now?: Date; +}): DayRange | null { + if (opts.from && opts.to) { + const ordered = + opts.from <= opts.to + ? { from: opts.from, to: opts.to } + : { from: opts.to, to: opts.from }; + return clampSpan(ordered); + } + return resolveDayRange(opts.period, opts.periodStart, opts.now ?? new Date()); +} diff --git a/packages/trpc/src/router/leaderboard/queries.ts b/packages/trpc/src/router/leaderboard/queries.ts new file mode 100644 index 00000000000..dade388f6dc --- /dev/null +++ b/packages/trpc/src/router/leaderboard/queries.ts @@ -0,0 +1,484 @@ +import { db } from "@superset/db/client"; +import { + leaderboardDaily, + leaderboardParticipants, + users, +} from "@superset/db/schema"; +import { and, desc, eq, gt, gte, isNull, lte, sql } from "drizzle-orm"; +import { type LeaderboardPeriod, resolveWindow } from "./periods"; +import { type Tier, tierProgress } from "./tier"; +import type { + LeaderboardMetric, + LeaderboardStats, + ParticipantProfile, + StandingsResult, +} from "./types"; + +export type * from "./types"; + +export interface WindowOpts { + period: LeaderboardPeriod; + periodStart?: string; + from?: string; + to?: string; +} + +export const onTheBoard = and( + eq(leaderboardParticipants.visibility, "public"), + isNull(leaderboardParticipants.revokedAt), + isNull(leaderboardParticipants.flaggedAt), +); + +export async function getStandings( + opts: WindowOpts & { + metric: LeaderboardMetric; + limit: number; + offset: number; + }, +): Promise { + const range = resolveWindow(opts); + const byCost = opts.metric === "cost"; + + if (!range) { + const rows = await db + .select({ + handle: leaderboardParticipants.handle, + name: users.name, + tokens: leaderboardParticipants.tokens, + usd: leaderboardParticipants.usd, + sessions: leaderboardParticipants.sessions, + approximate: leaderboardParticipants.approximate, + tier: leaderboardParticipants.tier, + }) + .from(leaderboardParticipants) + .innerJoin(users, eq(users.id, leaderboardParticipants.userId)) + + .where( + and( + onTheBoard, + isNull(users.deletedAt), + gt(leaderboardParticipants.tokens, 0), + ), + ) + .orderBy( + desc( + byCost ? leaderboardParticipants.usd : leaderboardParticipants.tokens, + ), + leaderboardParticipants.userId, + ) + .limit(opts.limit) + .offset(opts.offset); + + const [counted] = await db + .select({ participants: sql`count(*)::int` }) + .from(leaderboardParticipants) + .innerJoin(users, eq(users.id, leaderboardParticipants.userId)) + .where( + and( + onTheBoard, + isNull(users.deletedAt), + gt(leaderboardParticipants.tokens, 0), + ), + ); + const participantCount = Number(counted?.participants ?? 0); + + return { + period: opts.period, + metric: opts.metric, + range: null, + total: participantCount, + hasMore: opts.offset + rows.length < participantCount, + rows: rows.map((row, index) => ({ + ...row, + tokens: Number(row.tokens), + sessions: Number(row.sessions), + rank: opts.offset + index + 1, + })), + }; + } + + const total = sql`sum(${leaderboardDaily.tokens})`; + const spend = sql`sum(${leaderboardDaily.usdEstimate})`; + const rows = await db + .select({ + handle: leaderboardParticipants.handle, + name: users.name, + tokens: sql`${total}::bigint`, + usd: sql`sum(${leaderboardDaily.usdEstimate})`, + sessions: sql`sum(${leaderboardDaily.sessions})::int`, + approximate: sql`bool_or(${leaderboardDaily.approximate})`, + tier: leaderboardParticipants.tier, + }) + .from(leaderboardDaily) + .innerJoin( + leaderboardParticipants, + eq(leaderboardParticipants.userId, leaderboardDaily.userId), + ) + .innerJoin(users, eq(users.id, leaderboardParticipants.userId)) + .where( + and( + gte(leaderboardDaily.day, range.from), + lte(leaderboardDaily.day, range.to), + onTheBoard, + isNull(users.deletedAt), + ), + ) + .groupBy( + leaderboardDaily.userId, + leaderboardParticipants.handle, + leaderboardParticipants.tier, + users.name, + ) + .orderBy(desc(byCost ? spend : total), leaderboardDaily.userId) + .limit(opts.limit) + .offset(opts.offset); + + const [counted] = await db + .select({ + participants: sql`count(distinct ${leaderboardDaily.userId})::int`, + }) + .from(leaderboardDaily) + .innerJoin( + leaderboardParticipants, + eq(leaderboardParticipants.userId, leaderboardDaily.userId), + ) + .innerJoin(users, eq(users.id, leaderboardParticipants.userId)) + .where( + and( + gte(leaderboardDaily.day, range.from), + lte(leaderboardDaily.day, range.to), + onTheBoard, + isNull(users.deletedAt), + ), + ); + const participantCount = Number(counted?.participants ?? 0); + + return { + period: opts.period, + metric: opts.metric, + range, + total: participantCount, + hasMore: opts.offset + rows.length < participantCount, + rows: rows.map((row, index) => ({ + ...row, + tokens: Number(row.tokens), + sessions: Number(row.sessions), + tier: Number(row.tier), + rank: opts.offset + index + 1, + })), + }; +} + +const TOP_MODELS = 20; + +async function getTierDistribution(): Promise { + const rows = await db + .select({ + tier: leaderboardParticipants.tier, + participants: sql`count(*)::int`, + }) + .from(leaderboardParticipants) + .innerJoin(users, eq(users.id, leaderboardParticipants.userId)) + .where(and(onTheBoard, isNull(users.deletedAt))) + .groupBy(leaderboardParticipants.tier); + + const distribution = [0, 0, 0, 0, 0]; + for (const row of rows) { + const tier = Number(row.tier); + if (tier >= 0 && tier <= 4) { + distribution[tier] = (distribution[tier] ?? 0) + Number(row.participants); + } + } + + const ranked = distribution.slice(1).reduce((sum, n) => sum + n, 0); + + const weighted = distribution.reduce( + (sum, count, tier) => sum + count * tier, + 0, + ); + const position = ranked > 0 ? Number((weighted / ranked).toFixed(3)) : 0; + + let mode = 0; + let best = 0; + for (let tier = 1; tier <= 4; tier++) { + const count = distribution[tier] ?? 0; + if (count > best) { + best = count; + mode = tier; + } + } + + return { distribution, ranked, mode, position }; +} + +export async function getStats(opts: WindowOpts): Promise { + const range = resolveWindow(opts); + const tiers = await getTierDistribution(); + + const active = and(onTheBoard, isNull(users.deletedAt)); + const window = range + ? and( + gte(leaderboardDaily.day, range.from), + lte(leaderboardDaily.day, range.to), + active, + ) + : active; + + const [totalsRow] = await db + .select({ + participants: sql`count(distinct ${leaderboardDaily.userId})::int`, + tokens: sql`coalesce(sum(${leaderboardDaily.tokens}), 0)::bigint`, + usd: sql`coalesce(sum(${leaderboardDaily.usdEstimate}), 0)`, + + sessions: sql`coalesce(sum(${leaderboardDaily.sessions}), 0)::int`, + uncachedInput: sql`coalesce(sum(${leaderboardDaily.uncachedInput}), 0)::bigint`, + cachedInput: sql`coalesce(sum(${leaderboardDaily.cachedInput}), 0)::bigint`, + cacheWrite5m: sql`coalesce(sum(${leaderboardDaily.cacheWrite5m}), 0)::bigint`, + cacheWrite1h: sql`coalesce(sum(${leaderboardDaily.cacheWrite1h}), 0)::bigint`, + output: sql`coalesce(sum(${leaderboardDaily.output}), 0)::bigint`, + reasoningOutput: sql`coalesce(sum(${leaderboardDaily.reasoningOutput}), 0)::bigint`, + }) + .from(leaderboardDaily) + .innerJoin( + leaderboardParticipants, + eq(leaderboardParticipants.userId, leaderboardDaily.userId), + ) + .innerJoin(users, eq(users.id, leaderboardParticipants.userId)) + .where(window); + + const modelUsers = await db + .select({ + provider: leaderboardDaily.provider, + model: leaderboardDaily.model, + users: sql`count(distinct ${leaderboardDaily.userId})::int`, + }) + .from(leaderboardDaily) + .innerJoin( + leaderboardParticipants, + eq(leaderboardParticipants.userId, leaderboardDaily.userId), + ) + .innerJoin(users, eq(users.id, leaderboardParticipants.userId)) + .where(window) + .groupBy(leaderboardDaily.provider, leaderboardDaily.model) + .orderBy(desc(sql`count(distinct ${leaderboardDaily.userId})`)) + .limit(TOP_MODELS); + + const modelSpend = await db + .select({ + provider: leaderboardDaily.provider, + model: leaderboardDaily.model, + usd: sql`sum(${leaderboardDaily.usdEstimate})`, + tokens: sql`sum(${leaderboardDaily.tokens})::bigint`, + }) + .from(leaderboardDaily) + .innerJoin( + leaderboardParticipants, + eq(leaderboardParticipants.userId, leaderboardDaily.userId), + ) + .innerJoin(users, eq(users.id, leaderboardParticipants.userId)) + .where(window) + .groupBy(leaderboardDaily.provider, leaderboardDaily.model) + .orderBy(desc(sql`sum(${leaderboardDaily.usdEstimate})`)) + .limit(TOP_MODELS); + + const modelTokens = await db + .select({ + provider: leaderboardDaily.provider, + model: leaderboardDaily.model, + usd: sql`sum(${leaderboardDaily.usdEstimate})`, + tokens: sql`sum(${leaderboardDaily.tokens})::bigint`, + }) + .from(leaderboardDaily) + .innerJoin( + leaderboardParticipants, + eq(leaderboardParticipants.userId, leaderboardDaily.userId), + ) + .innerJoin(users, eq(users.id, leaderboardParticipants.userId)) + .where(window) + .groupBy(leaderboardDaily.provider, leaderboardDaily.model) + .orderBy(desc(sql`sum(${leaderboardDaily.tokens})`)) + .limit(TOP_MODELS); + + return { + period: opts.period, + range, + totals: { + participants: Number(totalsRow?.participants ?? 0), + tokens: Number(totalsRow?.tokens ?? 0), + usd: String(totalsRow?.usd ?? "0"), + sessions: Number(totalsRow?.sessions ?? 0), + }, + tokenSplit: { + uncachedInput: Number(totalsRow?.uncachedInput ?? 0), + cachedInput: Number(totalsRow?.cachedInput ?? 0), + cacheWrite5m: Number(totalsRow?.cacheWrite5m ?? 0), + cacheWrite1h: Number(totalsRow?.cacheWrite1h ?? 0), + output: Number(totalsRow?.output ?? 0), + reasoningOutput: Number(totalsRow?.reasoningOutput ?? 0), + }, + models: { + byUsers: modelUsers.map((row) => ({ ...row, users: Number(row.users) })), + bySpend: modelSpend.map((row) => ({ + ...row, + tokens: Number(row.tokens), + })), + byTokens: modelTokens.map((row) => ({ + ...row, + tokens: Number(row.tokens), + })), + }, + tiers, + }; +} + +const PROFILE_TOP_MODELS = 8; + +export async function getParticipant( + handle: string, + opts: WindowOpts, +): Promise { + const [participant] = await db + .select({ + userId: leaderboardParticipants.userId, + handle: leaderboardParticipants.handle, + name: users.name, + joinedAt: leaderboardParticipants.optedInAt, + lastPublishedAt: leaderboardParticipants.lastPublishedAt, + dayRangeStart: leaderboardParticipants.dayRangeStart, + dayRangeEnd: leaderboardParticipants.dayRangeEnd, + tokens: leaderboardParticipants.tokens, + usd: leaderboardParticipants.usd, + sessions: leaderboardParticipants.sessions, + approximate: leaderboardParticipants.approximate, + tier: leaderboardParticipants.tier, + tierComputedAt: leaderboardParticipants.tierComputedAt, + activeDays: leaderboardParticipants.activeDays, + axisWidth: leaderboardParticipants.axisWidth, + axisDepth: leaderboardParticipants.axisDepth, + axisOutput: leaderboardParticipants.axisOutput, + }) + .from(leaderboardParticipants) + .innerJoin(users, eq(users.id, leaderboardParticipants.userId)) + .where( + and( + eq(leaderboardParticipants.handle, handle.toLowerCase()), + onTheBoard, + isNull(users.deletedAt), + ), + ) + .limit(1); + + if (!participant) return null; + + const range = resolveWindow(opts); + const inWindow = range + ? and( + eq(leaderboardDaily.userId, participant.userId), + gte(leaderboardDaily.day, range.from), + lte(leaderboardDaily.day, range.to), + ) + : eq(leaderboardDaily.userId, participant.userId); + + const [windowTotals] = await db + .select({ + tokens: sql`coalesce(sum(${leaderboardDaily.tokens}), 0)::bigint`, + usd: sql`coalesce(sum(${leaderboardDaily.usdEstimate}), 0)`, + sessions: sql`coalesce(sum(${leaderboardDaily.sessions}), 0)::int`, + uncachedInput: sql`coalesce(sum(${leaderboardDaily.uncachedInput}), 0)::bigint`, + cachedInput: sql`coalesce(sum(${leaderboardDaily.cachedInput}), 0)::bigint`, + cacheWrite5m: sql`coalesce(sum(${leaderboardDaily.cacheWrite5m}), 0)::bigint`, + cacheWrite1h: sql`coalesce(sum(${leaderboardDaily.cacheWrite1h}), 0)::bigint`, + output: sql`coalesce(sum(${leaderboardDaily.output}), 0)::bigint`, + reasoningOutput: sql`coalesce(sum(${leaderboardDaily.reasoningOutput}), 0)::bigint`, + }) + .from(leaderboardDaily) + .where(inWindow); + + const models = await db + .select({ + provider: leaderboardDaily.provider, + model: leaderboardDaily.model, + tokens: sql`sum(${leaderboardDaily.tokens})::bigint`, + usd: sql`sum(${leaderboardDaily.usdEstimate})`, + }) + .from(leaderboardDaily) + .where(inWindow) + .groupBy(leaderboardDaily.provider, leaderboardDaily.model) + .orderBy(desc(sql`sum(${leaderboardDaily.tokens})`)) + .limit(PROFILE_TOP_MODELS); + + const daily = await db + .select({ + day: leaderboardDaily.day, + tokens: sql`sum(${leaderboardDaily.tokens})::bigint`, + usd: sql`sum(${leaderboardDaily.usdEstimate})`, + }) + .from(leaderboardDaily) + .where(inWindow) + .groupBy(leaderboardDaily.day) + .orderBy(leaderboardDaily.day); + + const [ranked] = await db + .select({ + ahead: sql`count(*) filter (where ${leaderboardParticipants.tokens} > ${participant.tokens})::int`, + total: sql`count(*)::int`, + }) + .from(leaderboardParticipants) + .innerJoin(users, eq(users.id, leaderboardParticipants.userId)) + .where( + and( + onTheBoard, + isNull(users.deletedAt), + gt(leaderboardParticipants.tokens, 0), + ), + ); + + return { + handle: participant.handle, + name: participant.name, + joinedAt: participant.joinedAt, + lastPublishedAt: participant.lastPublishedAt, + dayRange: + participant.dayRangeStart && participant.dayRangeEnd + ? { from: participant.dayRangeStart, to: participant.dayRangeEnd } + : null, + allTime: { + tokens: Number(participant.tokens), + usd: String(participant.usd), + sessions: Number(participant.sessions), + approximate: participant.approximate, + }, + window: { + range, + tokens: Number(windowTotals?.tokens ?? 0), + usd: String(windowTotals?.usd ?? "0"), + sessions: Number(windowTotals?.sessions ?? 0), + }, + rank: Number(ranked?.ahead ?? 0) + 1, + total: + Number(ranked?.total ?? 0) + (Number(participant.tokens) > 0 ? 0 : 1), + factory: { + tier: Number(participant.tier), + progress: tierProgress( + { + width: Number(participant.axisWidth), + depth: Number(participant.axisDepth), + output: Number(participant.axisOutput), + sustain: Number(participant.activeDays), + }, + Number(participant.tier) as Tier, + ), + computedAt: participant.tierComputedAt, + }, + tokenSplit: { + uncachedInput: Number(windowTotals?.uncachedInput ?? 0), + cachedInput: Number(windowTotals?.cachedInput ?? 0), + cacheWrite5m: Number(windowTotals?.cacheWrite5m ?? 0), + cacheWrite1h: Number(windowTotals?.cacheWrite1h ?? 0), + output: Number(windowTotals?.output ?? 0), + reasoningOutput: Number(windowTotals?.reasoningOutput ?? 0), + }, + models: models.map((row) => ({ ...row, tokens: Number(row.tokens) })), + daily: daily.map((row) => ({ ...row, tokens: Number(row.tokens) })), + }; +} diff --git a/packages/trpc/src/router/leaderboard/schema.ts b/packages/trpc/src/router/leaderboard/schema.ts new file mode 100644 index 00000000000..1e198519a75 --- /dev/null +++ b/packages/trpc/src/router/leaderboard/schema.ts @@ -0,0 +1,118 @@ +import { z } from "zod"; +import { isDayKey, LEADERBOARD_PERIODS } from "./periods"; + +const dayKey = z.string().refine(isDayKey, "Expected a real YYYY-MM-DD date"); + +// Per field, per (day, provider, model, host) row. Generous next to real usage, +// but low enough that a full payload cannot overflow the bigint rollup on +// leaderboard_participants. +export const MAX_TOKENS_PER_ROW_FIELD = 50_000_000_000; + +const tokenCount = z.number().int().min(0).max(MAX_TOKENS_PER_ROW_FIELD); + +export const handleSchema = z + .string() + .trim() + .toLowerCase() + .min(2) + .max(39) + .regex( + /^[a-z0-9](?:[a-z0-9]|-(?=[a-z0-9])){0,38}$/, + "Letters, numbers and single dashes only", + ); + +export const visibilitySchema = z.enum(["public", "hidden"]); + +export const periodSchema = z.enum(LEADERBOARD_PERIODS); + +export const joinSchema = z.object({ + handle: handleSchema, + visibility: visibilitySchema.default("public"), +}); + +// Same reasoning as the token cap, against the numeric(14,6) usd rollup. +export const MAX_USD_PER_ROW = 10_000; + +export const publishDaySchema = z.object({ + day: dayKey, + provider: z.string().min(1).max(64), + model: z.string().min(1).max(128), + uncachedInput: tokenCount, + cachedInput: tokenCount, + cacheWrite5m: tokenCount, + cacheWrite1h: tokenCount, + output: tokenCount, + reasoningOutput: tokenCount, + usdEstimate: z.number().min(0).max(MAX_USD_PER_ROW), + approximate: z.boolean(), + sessions: z.number().int().min(0).max(100_000), +}); + +export type PublishDay = z.infer; + +export const publishFactoryDaySchema = z.object({ + day: dayKey, + sessions: z.number().int().min(0).max(100_000), + + parallelSessions: z.number().min(0).max(10_000), + agentPrsMerged: z.number().int().min(0).max(10_000), +}); + +export type PublishFactoryDay = z.infer; + +// Rows, not days: 36 days x ~55 provider/model combos. Also keeps the insert +// under Postgres's 65,535 bind parameters at 15 columns per row. +export const PUBLISH_MAX_DAYS = 2_000; + +// The widest a client legitimately reaches back is the 30-day join backfill; +// the extra days absorb host/server clock skew around a UTC midnight. +export const PUBLISH_WINDOW_DAYS = 35; + +// hostId is a free-form client string and part of the upsert key, so without a +// bound the per-row caps above can be multiplied by inventing hosts. +export const MAX_HOSTS_PER_USER = 10; + +export const PUBLISH_PAYLOAD_VERSION = 2; + +export const publishSchema = z.object({ + payloadVersion: z.union([z.literal(1), z.literal(2)]), + hostId: z.string().min(1).max(128), + days: z.array(publishDaySchema).max(PUBLISH_MAX_DAYS), + factoryDays: z + .array(publishFactoryDaySchema) + .max(PUBLISH_MAX_DAYS) + .default([]), +}); + +export const metricSchema = z.enum(["tokens", "cost"]); + +export const windowSchema = z.object({ + period: periodSchema.default("30d"), + periodStart: dayKey.optional(), + from: dayKey.optional(), + to: dayKey.optional(), +}); + +export const standingsSchema = windowSchema.extend({ + metric: metricSchema.default("tokens"), + limit: z.number().int().min(1).max(100).default(50), + // OFFSET is O(n) over a grouped aggregate on an anonymous endpoint; the board + // only pages sequentially, so deep scans are abuse rather than use. + offset: z.number().int().min(0).max(1_000).default(0), +}); + +export const participantSchema = windowSchema.extend({ + handle: handleSchema, + period: periodSchema.default("all"), +}); + +export const previewRankSchema = z.object({ + period: periodSchema.default("month"), + periodStart: dayKey.optional(), + tokens: tokenCount, +}); + +export const meSchema = z.object({ + period: periodSchema.default("month"), + periodStart: dayKey.optional(), +}); diff --git a/packages/trpc/src/router/leaderboard/tier.test.ts b/packages/trpc/src/router/leaderboard/tier.test.ts new file mode 100644 index 00000000000..39e128e4b3d --- /dev/null +++ b/packages/trpc/src/router/leaderboard/tier.test.ts @@ -0,0 +1,170 @@ +import { describe, expect, test } from "bun:test"; +import { + computeTier, + depthTier, + type FactoryDayRow, + outputTier, + sustainTier, + tierName, + tierProgress, + widthTier, +} from "./tier"; + +function days( + count: number, + over: Partial = {}, + from = "2026-08-01", +): FactoryDayRow[] { + const start = Date.parse(`${from}T00:00:00Z`); + return Array.from({ length: count }, (_, i) => ({ + day: new Date(start + i * 86_400_000).toISOString().slice(0, 10), + tokens: 24_000_000, + sessions: 8, + parallelSessions: 3, + agentPrsMerged: 1, + ...over, + })); +} + +describe("axis floors", () => { + test("width quotes the essay's 3 and 10", () => { + expect(widthTier(2)).toBe(2); + expect(widthTier(3)).toBe(3); + expect(widthTier(9)).toBe(3); + expect(widthTier(10)).toBe(4); + }); + + test("width 0 is unranked, not tier 1", () => { + expect(widthTier(0)).toBe(0); + }); + + test("depth grades tokens per session", () => { + expect(depthTier(100_000)).toBe(1); + expect(depthTier(500_000)).toBe(2); + expect(depthTier(8_000_000)).toBe(4); + }); + + test("output grades weekly merged agent PRs", () => { + expect(outputTier(0)).toBe(1); + expect(outputTier(3)).toBe(3); + expect(outputTier(10)).toBe(4); + }); + + test("sustain needs 8 active days to rank at all", () => { + expect(sustainTier(7)).toBe(0); + expect(sustainTier(8)).toBe(1); + expect(sustainTier(20)).toBe(4); + }); +}); + +describe("computeTier", () => { + test("fewer than 8 active days is unranked", () => { + expect(computeTier(days(7)).tier).toBe(0); + }); + + test("takes the MIN across axes, not the average", () => { + const result = computeTier( + days(20, { + parallelSessions: 14, + tokens: 200_000_000, + sessions: 10, + agentPrsMerged: 0, + }), + ); + expect(result.tier).toBe(1); + expect(result.limitedBy).toContain("output"); + }); + + test("all axes strong reaches Henry Ford", () => { + const result = computeTier( + days(22, { + parallelSessions: 12, + tokens: 120_000_000, + sessions: 10, + agentPrsMerged: 2, + }), + ); + expect(result.tier).toBe(4); + expect(tierName(result.tier)).toBe("Henry Ford"); + }); + + test("activeDays caps the tier however good the days are", () => { + const strong = { + parallelSessions: 12, + tokens: 120_000_000, + sessions: 10, + agentPrsMerged: 2, + }; + expect(computeTier(days(22, strong)).tier).toBe(4); + expect(computeTier(days(9, strong)).tier).toBe(1); + }); + + test("output reads a trailing 7-day rate, not a single day", () => { + const rows = days(20, { agentPrsMerged: 0 }); + for (let i = 0; i < rows.length; i += 7) { + const row = rows[i]; + if (row) row.agentPrsMerged = 3; + } + expect(computeTier(rows).tier).toBe(3); + }); + + test("holds the previous tier through a dip rather than flapping", () => { + const mixed = [ + ...days(11, { parallelSessions: 3 }), + ...days(9, { parallelSessions: 1 }, "2026-08-12"), + ]; + expect(computeTier(mixed, 3).tier).toBe(3); + expect(computeTier(mixed, 0).tier).toBe(1); + }); + + test("demotes once the current tier drops under 40% of active days", () => { + const collapsed = [ + ...days(3, { parallelSessions: 3 }), + ...days(17, { parallelSessions: 1 }, "2026-08-04"), + ]; + expect(computeTier(collapsed, 3).tier).toBe(1); + }); + + test("tokens alone cannot buy a tier", () => { + const result = computeTier( + days(20, { + parallelSessions: 1, + tokens: 900_000_000, + sessions: 1, + agentPrsMerged: 20, + }), + ); + expect(result.tier).toBe(1); + expect(result.limitedBy).toContain("width"); + }); +}); + +describe("tierProgress", () => { + const full = { width: 10, depth: 8e6, output: 10, sustain: 20 }; + + test("unranked has no progress", () => { + expect(tierProgress(full, 0)).toBe(0); + }); + + test("the top tier is complete", () => { + expect(tierProgress(full, 4)).toBe(1); + }); + + test("halfway on every axis reads as halfway", () => { + expect( + tierProgress({ width: 1.5, depth: 250_000, output: 0.5, sustain: 9 }, 1), + ).toBe(0.5); + }); + + test("the weakest axis governs, not the average", () => { + expect( + tierProgress({ width: 2, depth: 500_000, output: 1, sustain: 8 }, 1), + ).toBe(0); + }); + + test("overshooting an axis does not push past the next station", () => { + expect( + tierProgress({ width: 99, depth: 9e9, output: 99, sustain: 30 }, 1), + ).toBe(1); + }); +}); diff --git a/packages/trpc/src/router/leaderboard/tier.ts b/packages/trpc/src/router/leaderboard/tier.ts new file mode 100644 index 00000000000..72c15a96a86 --- /dev/null +++ b/packages/trpc/src/router/leaderboard/tier.ts @@ -0,0 +1,194 @@ +export const TIER_NAMES = [ + "Button pusher", + "Operator", + "Plant Manager", + "Henry Ford", +] as const; + +export type TierName = (typeof TIER_NAMES)[number]; + +export type Tier = 0 | 1 | 2 | 3 | 4; + +export const tierName = (tier: Tier): TierName | null => + tier === 0 ? null : (TIER_NAMES[tier - 1] ?? null); + +export const FLOORS = { + width: [1, 2, 3, 10], + depth: [0, 500_000, 2_000_000, 8_000_000], + output: [0, 1, 3, 10], + sustain: [8, 10, 15, 20], +} as const; + +const MIN_ACTIVE_DAYS = FLOORS.sustain[0]; +const PROMOTE_SHARE = 0.6; +const DEMOTE_SHARE = 0.4; +const OUTPUT_WINDOW_DAYS = 7; + +function floorTier(value: number, floors: readonly number[]): Tier { + let tier = 0; + for (let i = 0; i < floors.length; i++) { + if (value >= (floors[i] ?? Number.POSITIVE_INFINITY)) tier = i + 1; + } + return tier as Tier; +} + +export const widthTier = (parallelSessions: number): Tier => + floorTier(parallelSessions, FLOORS.width); +export const depthTier = (tokensPerSession: number): Tier => + floorTier(tokensPerSession, FLOORS.depth); +export const outputTier = (agentPrsPerWeek: number): Tier => + floorTier(agentPrsPerWeek, FLOORS.output); +export const sustainTier = (activeDays: number): Tier => + floorTier(activeDays, FLOORS.sustain); + +export interface FactoryDayRow { + day: string; + tokens: number; + sessions: number; + parallelSessions: number; + agentPrsMerged: number; +} + +export interface TierResult { + tier: Tier; + activeDays: number; + axisWidth: number; + axisDepth: number; + axisOutput: number; + + limitedBy: Array<"width" | "depth" | "output" | "sustain">; +} + +const UNRANKED: TierResult = { + tier: 0, + activeDays: 0, + axisWidth: 0, + axisDepth: 0, + axisOutput: 0, + limitedBy: ["sustain"], +}; + +function median(values: number[]): number { + if (values.length === 0) return 0; + const sorted = [...values].sort((a, b) => a - b); + const mid = sorted.length >> 1; + if (sorted.length % 2 === 1) return sorted[mid] ?? 0; + return ((sorted[mid - 1] ?? 0) + (sorted[mid] ?? 0)) / 2; +} + +const dayIndex = (day: string) => + Math.floor(Date.parse(`${day}T00:00:00Z`) / 86_400_000); + +function trailingOutput(rows: FactoryDayRow[], at: number): number { + const end = dayIndex(rows[at]?.day ?? ""); + let total = 0; + for (let i = at; i >= 0; i--) { + const row = rows[i]; + if (!row) break; + if (end - dayIndex(row.day) >= OUTPUT_WINDOW_DAYS) break; + total += row.agentPrsMerged; + } + return total; +} + +export function computeTier( + rows: FactoryDayRow[], + previousTier: Tier = 0, +): TierResult { + const active = [...rows].sort((a, b) => (a.day < b.day ? -1 : 1)); + const activeDays = active.length; + if (activeDays < MIN_ACTIVE_DAYS) return { ...UNRANKED, activeDays }; + + const widths: number[] = []; + const depths: number[] = []; + const outputs: number[] = []; + const dailyTiers: Tier[] = []; + + for (let i = 0; i < active.length; i++) { + const row = active[i]; + if (!row) continue; + const depth = row.sessions > 0 ? row.tokens / row.sessions : 0; + const output = trailingOutput(active, i); + widths.push(row.parallelSessions); + depths.push(depth); + outputs.push(output); + dailyTiers.push( + Math.min( + widthTier(row.parallelSessions), + depthTier(depth), + outputTier(output), + ) as Tier, + ); + } + + const share = (tier: number) => + dailyTiers.filter((t) => t >= tier).length / activeDays; + + let promotable = 0; + let held = 0; + for (let tier = 4; tier >= 1; tier--) { + if (promotable === 0 && share(tier) >= PROMOTE_SHARE) promotable = tier; + if (held === 0 && share(tier) >= DEMOTE_SHARE) held = tier; + } + + const dayTier = + promotable > previousTier + ? promotable + : held < previousTier + ? held + : previousTier; + + const sustain = sustainTier(activeDays); + const tier = Math.min(dayTier, sustain) as Tier; + + const axisWidth = median(widths); + const axisDepth = median(depths); + const axisOutput = median(outputs); + + const limitedBy: TierResult["limitedBy"] = []; + if (tier < 4) { + if (widthTier(axisWidth) === tier) limitedBy.push("width"); + if (depthTier(axisDepth) === tier) limitedBy.push("depth"); + if (outputTier(axisOutput) === tier) limitedBy.push("output"); + if (sustain === tier) limitedBy.push("sustain"); + } + + return { + tier, + activeDays, + axisWidth: Number(axisWidth.toFixed(2)), + axisDepth: Math.round(axisDepth), + axisOutput: Number(axisOutput.toFixed(2)), + limitedBy, + }; +} + +export interface AxisValues { + width: number; + depth: number; + output: number; + sustain: number; +} + +export function tierProgress(values: AxisValues, tier: Tier): number { + if (tier <= 0) return 0; + if (tier >= 4) return 1; + + const axes: Array<[number, readonly number[]]> = [ + [values.width, FLOORS.width], + [values.depth, FLOORS.depth], + [values.output, FLOORS.output], + [values.sustain, FLOORS.sustain], + ]; + + let lowest = 1; + for (const [value, floors] of axes) { + const from = floors[tier - 1] ?? 0; + const to = floors[tier] ?? from; + const span = to - from; + const progress = + span <= 0 ? 1 : Math.min(1, Math.max(0, (value - from) / span)); + lowest = Math.min(lowest, progress); + } + return Number(lowest.toFixed(3)); +} diff --git a/packages/trpc/src/router/leaderboard/types.ts b/packages/trpc/src/router/leaderboard/types.ts new file mode 100644 index 00000000000..c43af49aeed --- /dev/null +++ b/packages/trpc/src/router/leaderboard/types.ts @@ -0,0 +1,102 @@ +import type { DayRange, LeaderboardPeriod } from "./periods"; + +export type LeaderboardMetric = "tokens" | "cost"; + +export interface StandingRow { + rank: number; + handle: string; + name: string | null; + tokens: number; + usd: string; + sessions: number; + approximate: boolean; + tier: number; +} + +export interface StandingsResult { + period: LeaderboardPeriod; + metric: LeaderboardMetric; + range: DayRange | null; + rows: StandingRow[]; + total: number; + hasMore: boolean; +} + +export interface TierDistribution { + distribution: number[]; + ranked: number; + mode: number; + position: number; +} + +export interface TokenSplit { + uncachedInput: number; + cachedInput: number; + cacheWrite5m: number; + cacheWrite1h: number; + output: number; + reasoningOutput: number; +} + +export interface LeaderboardStats { + period: LeaderboardPeriod; + range: DayRange | null; + totals: { + participants: number; + tokens: number; + usd: string; + sessions: number; + }; + tokenSplit: TokenSplit; + models: { + byUsers: Array<{ provider: string; model: string; users: number }>; + bySpend: Array<{ + provider: string; + model: string; + usd: string; + tokens: number; + }>; + byTokens: Array<{ + provider: string; + model: string; + usd: string; + tokens: number; + }>; + }; + tiers: TierDistribution; +} + +export interface ParticipantProfile { + handle: string; + name: string | null; + joinedAt: Date; + lastPublishedAt: Date | null; + dayRange: DayRange | null; + allTime: { + tokens: number; + usd: string; + sessions: number; + approximate: boolean; + }; + window: { + range: DayRange | null; + tokens: number; + usd: string; + sessions: number; + }; + rank: number; + total: number; + factory: { + tier: number; + progress: number; + computedAt: Date | null; + }; + tokenSplit: TokenSplit; + models: Array<{ + provider: string; + model: string; + tokens: number; + usd: string; + }>; + daily: Array<{ day: string; tokens: number; usd: string }>; +} diff --git a/packages/trpc/src/router/utils/unique-violation.test.ts b/packages/trpc/src/router/utils/unique-violation.test.ts new file mode 100644 index 00000000000..1c63af939ca --- /dev/null +++ b/packages/trpc/src/router/utils/unique-violation.test.ts @@ -0,0 +1,45 @@ +import { describe, expect, test } from "bun:test"; +import { isUniqueViolation } from "./unique-violation"; + +const CONSTRAINT = "leaderboard_participants_handle_unique"; + +describe("isUniqueViolation", () => { + test("matches a bare driver error", () => { + expect( + isUniqueViolation({ code: "23505", constraint: CONSTRAINT }, CONSTRAINT), + ).toBe(true); + }); + + test("matches through a drizzle wrapper", () => { + const wrapped = new Error("query failed", { + cause: { code: "23505", constraint: CONSTRAINT }, + }); + expect(isUniqueViolation(wrapped, CONSTRAINT)).toBe(true); + }); + + test("ignores a different constraint", () => { + expect( + isUniqueViolation( + { code: "23505", constraint: "other_unique" }, + CONSTRAINT, + ), + ).toBe(false); + }); + + test("ignores a different error code", () => { + expect( + isUniqueViolation({ code: "23503", constraint: CONSTRAINT }, CONSTRAINT), + ).toBe(false); + }); + + test("terminates on a self-referential cause chain", () => { + const looped: { cause?: unknown } = {}; + looped.cause = looped; + expect(isUniqueViolation(looped, CONSTRAINT)).toBe(false); + }); + + test("handles null and primitives", () => { + expect(isUniqueViolation(null, CONSTRAINT)).toBe(false); + expect(isUniqueViolation("boom", CONSTRAINT)).toBe(false); + }); +}); diff --git a/packages/trpc/src/router/utils/unique-violation.ts b/packages/trpc/src/router/utils/unique-violation.ts new file mode 100644 index 00000000000..1eb179b1359 --- /dev/null +++ b/packages/trpc/src/router/utils/unique-violation.ts @@ -0,0 +1,13 @@ +export function isUniqueViolation(error: unknown, constraint: string): boolean { + for ( + let current: unknown = error, depth = 0; + current !== null && typeof current === "object" && depth < 8; + current = (current as { cause?: unknown }).cause, depth += 1 + ) { + const candidate = current as { code?: string; constraint?: string }; + if (candidate.code === "23505" && candidate.constraint === constraint) { + return true; + } + } + return false; +}