diff --git a/README.md b/README.md index 9d2b662..9f62608 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ talks to the Smartloop API (`api.smartloop.ai`) from the browser. | Overview | `/dashboard` | Getting started, token usage and estimated savings | | Models | `/models` | The model catalogue and published benchmark scores | | Cloud models | `/cloud-models/usage`, `/cloud-models/history` | Credit usage and call history for cloud models | +| GPU boxes | `/gpushed` | [gpushed](https://gpushed.smartloop.ai) balance, top-ups, the current box, daily spend and GPU prices (from `api.smartloop.ai/v1/gpushed`) | | Settings | `/settings/tokens`, `/settings/websearch`, `/settings/billing` | Access tokens, web search, plan, credits and invoices | | Plans and payment | `/plans`, `/pricing`, `/upgrade`, `/payment/*` | Upgrade and Stripe Checkout return pages | | Account | `/profile` | Name, email and password | diff --git a/src/app/components/app-shell.tsx b/src/app/components/app-shell.tsx index 4619612..844cf5b 100644 --- a/src/app/components/app-shell.tsx +++ b/src/app/components/app-shell.tsx @@ -21,6 +21,7 @@ import TravelExploreIcon from '@mui/icons-material/TravelExplore'; import TerminalIcon from '@mui/icons-material/Terminal'; import CloudOutlinedIcon from '@mui/icons-material/CloudOutlined'; import HistoryIcon from '@mui/icons-material/History'; +import DeveloperBoardOutlinedIcon from '@mui/icons-material/DeveloperBoardOutlined'; import ReceiptLongOutlinedIcon from '@mui/icons-material/ReceiptLongOutlined'; import PersonOutlineIcon from '@mui/icons-material/PersonOutline'; import Logo from '@/app/components/logo'; @@ -33,6 +34,8 @@ const SIDEBAR_WIDTH = 248; // it does not need a header of its own. const NAV_GROUPS: { heading: string | null; + /** Shown to superusers only, for sections that haven't launched yet. */ + adminOnly?: boolean; items: { label: string; path: string; icon: typeof TravelExploreIcon }[]; }[] = [ { @@ -49,6 +52,12 @@ const NAV_GROUPS: { { label: 'Session History', path: '/cloud-models/history', icon: HistoryIcon }, ], }, + { + heading: 'GPU Boxes', + // TEMP: until gpushed launches (see src/app/gpushed/page.tsx). + adminOnly: true, + items: [{ label: 'gpushed', path: '/gpushed', icon: DeveloperBoardOutlinedIcon }], + }, { heading: 'Settings', items: [ @@ -63,7 +72,7 @@ const NAV_GROUPS: { }, ]; -function SidebarContent({ onNavigate }: { onNavigate?: () => void }) { +function SidebarContent({ isAdmin, onNavigate }: { isAdmin: boolean; onNavigate?: () => void }) { const router = useRouter(); const pathname = usePathname(); const { theme, toggleTheme } = useTheme(); @@ -80,7 +89,7 @@ function SidebarContent({ onNavigate }: { onNavigate?: () => void }) { - {NAV_GROUPS.map((group, gi) => ( + {NAV_GROUPS.filter((g) => isAdmin || !g.adminOnly).map((group, gi) => ( {group.heading && (
@@ -142,7 +151,7 @@ export default function AppShell({ user, children }: { user?: any; children: Rea className="hidden md:block fixed inset-y-0 left-0 z-30" sx={{ width: SIDEBAR_WIDTH, borderRight: '1px solid var(--border)', bgcolor: 'var(--surface)' }} > - + {/* Mobile drawer */} @@ -158,7 +167,7 @@ export default function AppShell({ user, children }: { user?: any; children: Rea className="md:hidden fixed inset-y-0 left-0 z-50" sx={{ width: SIDEBAR_WIDTH, borderRight: '1px solid var(--border)', bgcolor: 'var(--surface)' }} > - setDrawerOpen(false)} /> + setDrawerOpen(false)} /> )} diff --git a/src/app/constants.js b/src/app/constants.js index bb82b5d..c0f4c98 100644 --- a/src/app/constants.js +++ b/src/app/constants.js @@ -3,6 +3,8 @@ const BASE_URL = process.env.base_url || "https://api.smartloop.ai"; export const API_ENDPOINT = `${BASE_URL}/v1`; export const WS_ENDPOINT = `${BASE_URL}/ws`; +// gpushed (GPU boxes) is served under the same host, by its own Worker. +export const GPUSHED_ENDPOINT = `${BASE_URL}/v1/gpushed`; // Plan names, prices and feature copy live on the marketing site, not in this // app. Keeping a second copy here meant hand-syncing every price change (and diff --git a/src/app/gpushed/gpushed-section.tsx b/src/app/gpushed/gpushed-section.tsx new file mode 100644 index 0000000..f98c7c3 --- /dev/null +++ b/src/app/gpushed/gpushed-section.tsx @@ -0,0 +1,512 @@ +'use client'; + +/** + * GPU Boxes: the account's gpushed balance, its box, what it has spent and + * the GPUs it can run. + * + * gpushed (https://gpushed.smartloop.ai) gives each smartloop account a + * personal NVIDIA GPU machine, created and managed from a Mac with the + * `gpushed` CLI and paid from a prepaid balance. Its API lives at + * api.smartloop.ai/v1/gpushed and accepts the same session token as the rest + * of the app, so this page reads it directly: + * + * GET /me balance and the current box + * GET /usage?days=30 spend and top-ups per day (UTC) + * GET /ledger?kind=topup recent top-ups + * GET /plans GPUs and their hourly price + * POST /topup Stripe Checkout; return_url brings people back + * here with ?topup=done or ?topup=cancelled + * + * Boxes are created, stopped and deleted from the CLI, not here: the page + * shows the box and the commands rather than duplicating them. + */ + +import { useCallback, useEffect, useState } from 'react'; +import { Box, CircularProgress } from '@mui/material'; +import { userService } from '@/app/services/user.service'; +import { GPUSHED_ENDPOINT } from '@/app/constants'; +import { CodeBlock, Row, Section } from '@/app/components/rows'; + +const INSTALL = 'curl -fsSL gpushed.smartloop.ai/install.sh | bash'; +const TOPUP_AMOUNTS = [10, 25, 50, 100]; +const DAYS = 30; + +interface GpuBox { + id: string; + plan: string; + status: string; + zone: string | null; + ip: string | null; + ssh_user: string; + hourly_usd: string; + stopped_hourly_usd: string; + error: string | null; + created_at: number; +} + +interface Me { + email: string; + balance_usd: string; + balance_micros: number; + low_balance: boolean; + min_topup_usd: number; + box: GpuBox | null; +} + +interface Usage { + daily: { date: string; usage_usd: string; topup_usd: string }[]; + total_usage_usd: string; + total_topup_usd: string; +} + +interface Plan { + id: string; + label: string; + hourly_usd: string; + stopped_hourly_usd: string; +} + +interface Plans { + default: string; + region: string; + plans: Plan[]; +} + +interface TopupEntry { + amount_usd: string; + created_at: number; +} + +/** undefined while loading, null if the request failed. */ +type Loaded = T | null | undefined; + +async function get(path: string): Promise { + const r: Response | undefined = await userService.makeAuthenticatedRequest(`${GPUSHED_ENDPOINT}${path}`, { + method: 'GET', + }); + if (!r || !r.ok) return null; + return r.json(); +} + +const STATUS: Record = { + pending: { label: 'Creating', tone: 'warn' }, + starting: { label: 'Starting', tone: 'warn' }, + running: { label: 'Running', tone: 'ok' }, + stopping: { label: 'Stopping', tone: 'warn' }, + stopped: { label: 'Stopped', tone: 'muted' }, + destroying: { label: 'Deleting', tone: 'warn' }, + failed: { label: 'Failed', tone: 'danger' }, +}; + +const TONE_CLASS = { + ok: 'text-ok', + warn: 'text-warn border-warn-border bg-warn-soft', + danger: 'text-danger border-danger-border bg-danger-soft', + muted: 'text-muted', +}; + +const LINK_CLASS = 'text-accent-text hover:opacity-80 hover:underline font-medium transition-colors'; + +const dateTime = (sec: number) => + new Date(sec * 1000).toLocaleString(undefined, { + month: 'short', + day: 'numeric', + hour: 'numeric', + minute: '2-digit', + }); + +const shortDate = (isoDay: string) => + new Date(`${isoDay}T00:00:00Z`).toLocaleDateString(undefined, { month: 'short', day: 'numeric', timeZone: 'UTC' }); + +function Pending() { + return ; +} + +function Badge({ label, tone }: { label: string; tone: keyof typeof TONE_CLASS }) { + return ( + + {label} + + ); +} + +function Stat({ label, value }: { label: string; value: string }) { + return ( + +
{label}
+
{value}
+
+ ); +} + +/** The last DAYS days, oldest first, with zero for days without usage. */ +function lastDays(usage: Usage): { date: string; usd: number }[] { + const byDay = new Map(usage.daily.map((d) => [d.date, Number(d.usage_usd)])); + const out: { date: string; usd: number }[] = []; + const today = new Date(); + for (let i = DAYS - 1; i >= 0; i--) { + const d = new Date(Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate() - i)); + const key = d.toISOString().slice(0, 10); + out.push({ date: key, usd: byDay.get(key) ?? 0 }); + } + return out; +} + +/** + * Daily spend: one series, so no legend (the row label names it). Bars because + * each day is a discrete total and most days may be empty; 4px rounded tops on + * a shared baseline, a 2px gap between bars, and a hover tooltip per day with a + * hit target the full height of the plot. + */ +function SpendChart({ usage }: { usage: Usage }) { + const days = lastDays(usage); + const max = Math.max(...days.map((d) => d.usd)); + const [hover, setHover] = useState(null); + + if (max <= 0) { + return

No GPU usage in the last {DAYS} days.

; + } + + const h = days[hover ?? -1]; + return ( + + setHover(null)}> + {days.map((d, i) => ( + setHover(i)} + aria-label={`${shortDate(d.date)}: $${d.usd.toFixed(2)}`} + > + 0 ? `max(2px, ${(d.usd / max) * 100}%)` : 0, + bgcolor: 'var(--accent-strong)', + opacity: hover === null || hover === i ? 1 : 0.45, + }} + /> + + ))} + {h && ( + + {shortDate(h.date)}{' '} + ${h.usd.toFixed(2)} + + )} + + + {shortDate(days[0].date)} + Today + + + ); +} + +function BoxRow({ box, plans }: { box: GpuBox; plans: Loaded }) { + const status = STATUS[box.status] ?? { label: box.status, tone: 'muted' as const }; + const plan = plans?.plans.find((p) => p.id === box.plan); + const price = box.status === 'stopped' ? `$${box.stopped_hourly_usd}/h while stopped (disk only)` : `$${box.hourly_usd}/h`; + return ( + + + + + {plan?.label ?? box.plan} + + +
+ {price} + {box.zone ? ` · ${box.zone}` : ''} + {box.ip ? ` · ${box.ip}` : ''} + {` · created ${dateTime(box.created_at)}`} +
+ {box.error &&
{box.error}
} +
+

+ Manage it from your Mac: gpushed ssh,{' '} + gpushed stop (only the disk is billed while stopped),{' '} + gpushed start, or gpushed down to + delete it. +

+
+
+ ); +} + +function NoBoxRow() { + const [copied, setCopied] = useState(false); + return ( + + { + navigator.clipboard?.writeText(INSTALL).then(() => { + setCopied(true); + setTimeout(() => setCopied(false), 1500); + }); + }} + /> + + ); +} + +function TopupControl({ me }: { me: Me }) { + const amounts = TOPUP_AMOUNTS.filter((a) => a >= me.min_topup_usd); + const [amount, setAmount] = useState(amounts[1] ?? amounts[0] ?? me.min_topup_usd); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + + const topup = async () => { + setBusy(true); + setError(null); + try { + const r: Response | undefined = await userService.makeAuthenticatedRequest(`${GPUSHED_ENDPOINT}/topup`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + amount_usd: amount, + return_url: `${window.location.origin}${window.location.pathname}`, + }), + }); + const body = r ? await r.json().catch(() => ({})) : {}; + if (r?.ok && body.url) { + window.location.href = body.url; + return; + } + setError(body.error ?? 'Could not start checkout. Try again.'); + } catch { + setError('Could not start checkout. Try again.'); + } + setBusy(false); + }; + + return ( + + + {amounts.map((a) => ( + + ))} + + + {error &&

{error}

} +
+ ); +} + +export default function GpushedSection({ user }: { user: any }) { + const [me, setMe] = useState>(undefined); + const [usage, setUsage] = useState>(undefined); + const [plans, setPlans] = useState>(undefined); + const [topups, setTopups] = useState>(undefined); + const [notice, setNotice] = useState(null); + + const loadMe = useCallback(() => get('/me').then(setMe).catch(() => setMe(null)), []); + + useEffect(() => { + if (!user) return; + loadMe(); + get(`/usage?days=${DAYS}`).then(setUsage).catch(() => setUsage(null)); + get('/plans').then(setPlans).catch(() => setPlans(null)); + get<{ entries: TopupEntry[] }>('/ledger?kind=topup') + .then((r) => setTopups(r ? r.entries : null)) + .catch(() => setTopups(null)); + }, [user, loadMe]); + + // Back from Stripe Checkout: the webhook credits the balance a few seconds + // after the payment, so check again a few times. + useEffect(() => { + if (!user) return; + const params = new URLSearchParams(window.location.search); + const result = params.get('topup'); + if (!result) return; + window.history.replaceState(null, '', window.location.pathname); + if (result === 'cancelled') { + setNotice('Top-up cancelled. You were not charged.'); + return; + } + setNotice('Payment received. Your balance updates in a few seconds.'); + const timers = [3000, 8000, 15000].map((ms) => setTimeout(loadMe, ms)); + return () => timers.forEach(clearTimeout); + }, [user, loadMe]); + + const failed = me === null || usage === null || plans === null || topups === null; + const empty = me && me.balance_micros <= 0; + + return ( +
+ {notice && ( + + +

{notice}

+
+
+ )} + + + + + {me ? ( + + ${me.balance_usd} + + ) : ( + <> + $— + {me === undefined && } + + )} + {me?.low_balance && } + {empty && } + + {me && } + + + + {me === undefined && ( + + + + Loading… + + + )} + {me && (me.box ? : )} + + {usage !== null && ( + + + + + + + + {usage ? ( + + ) : ( + + + Loading… + + )} + + + )} + + {topups !== null && ( + + {topups === undefined ? ( + + + Loading… + + ) : topups.length === 0 ? ( +

No top-ups yet.

+ ) : ( + + {topups.slice(0, 10).map((t) => ( + + {dateTime(t.created_at)} + +${t.amount_usd} + + ))} + + )} +
+ )} + + {plans !== null && ( + + Hourly prices while running; a stopped box costs only its disk. Details on{' '} + + gpushed.smartloop.ai + + . + + } + stacked + > + {plans === undefined ? ( + + + Loading… + + ) : ( + + {plans.plans.map((p) => ( + + +
+ {p.label} + {p.id === plans.default && ( + + + + )} +
+
+ gpushed up {p.id} +
+
+ ${p.hourly_usd}/h +
+ ))} +
+ )} +
+ )} + + {failed && ( + + +

Could not load your GPU box details. Try again in a moment.

+
+
+ )} +
+ ); +} diff --git a/src/app/gpushed/page.tsx b/src/app/gpushed/page.tsx new file mode 100644 index 0000000..857c636 --- /dev/null +++ b/src/app/gpushed/page.tsx @@ -0,0 +1,19 @@ +'use client'; + +import { useEffect } from 'react'; +import { useRouter } from 'next/navigation'; +import { useAuth } from '@/app/hooks/useAuth'; +import SettingsShell from '@/app/settings/settings-shell'; +import GpushedSection from '@/app/gpushed/gpushed-section'; + +// TEMP: superusers only until gpushed launches (its API isn't deployed yet). +// At launch, remove the redirect here and adminOnly on the sidebar group. +export default function GpushedPage() { + const [user] = useAuth(); + const router = useRouter(); + const denied = !!user && !user.admin; + useEffect(() => { + if (denied) router.replace('/dashboard'); + }, [denied, router]); + return {denied ? null : }; +}