Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ v41 Iris turns the current design, the Interactive Tour, or the Before / After c
### Glint Pro groundwork: waitlist, analytics, accounts and AI credits
Not a versioned release; groundwork for a paid plan (Glint Pro: hosted AI, lasting share links, sync). The studio itself stays free, and site copy must keep saying so. Glint Pro itself will be a later numbered release (v42 Junction shipped separately).

- **Accounts and hosted AI credits (Clerk + Neon; Supabase is gone).** Supabase was removed entirely, and cloud project and template sync, the community gallery (`gallery.js`) and live collaboration (`collab.js`) went with it; projects now live only in the browser. Sign-in is Clerk: `src/features/auth.js` loads Clerk's two browser bundles from the Clerk instance's own Frontend API (host decoded from the publishable key), so there is no Clerk package in the build; without a key no sign-in UI shows and nothing loads. It exports `getToken()`, `getUser()`, `onAuthChange()`, `openSignIn()`, `isConfigured()`; the header pill is a Sign in button or Clerk's own user button. The key is read at build time from `VITE_CLERK_PUBLISHABLE_KEY` or `NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY` (the name Clerk's Vercel Marketplace install adds; `vite.config.js` `envPrefix` lets it through). Server side, `api/_account.js` verifies the Clerk session token with `@clerk/backend` `verifyToken` (`CLERK_SECRET_KEY`, or `CLERK_JWT_KEY` for a networkless check) and keeps plans and credit counts in Neon Postgres through `@neondatabase/serverless` (`DATABASE_URL` or `POSTGRES_URL`). The schema is `api/_account-schema.js` (`subscriptions`, `ai_usage`, and the atomic `glint_use_credits(user, cost, free_limit, pro_limit)` function, keyed by Clerk's text user id); **the server installs it itself** the first time a query fails with a missing function or table, so there is no SQL to run by hand. `metered(kind, handler)` wraps the six hosted AI routes, spends credits before the model call (`CREDIT_COSTS`: 1 for text / vision / enhance / agent, 5 for an image) and refunds them when the route answers with an error. It answers `401 { code: 'sign_in' }` or `402 { code: 'no_credits' }`; a Clerk or database failure answers 503 (closed, not free). **Metering is on only when the deployment has a Clerk key and a database URL**; without them the routes behave as before. Limits default to 20 free and 500 Pro credits a month (`AI_FREE_CREDITS`, `AI_PRO_CREDITS`). `api/account.js` is one function for every account route (`?op=me` today; checkout, portal and the payment webhook go here, not in new files). In the editor, `src/features/account.js` `hostedFetch(path, body)` is the only way to call a hosted AI route: it adds the token, turns a sign-in or out-of-credits answer into a 501 (which every caller already treats as "use the person's own key") and shows why in a toast unless the person has their own key; the `#ai-credits` header chip shows credits left. **A new hosted AI route must be wrapped in `metered()` and called through `hostedFetch()`.** Tests use `ACCOUNT_STORE=memory` and sign throwaway Clerk-shaped tokens. Still to build: checkout + webhook (a merchant of record such as Lemon Squeezy), an account panel, share link perks, real prices.
- **Accounts and hosted AI credits (Clerk + Neon; Supabase is gone).** Supabase was removed entirely, and cloud project and template sync, the community gallery (`gallery.js`) and live collaboration (`collab.js`) went with it; projects now live only in the browser. Sign-in is Clerk: `src/features/auth.js` loads Clerk's two browser bundles from the Clerk instance's own Frontend API (host decoded from the publishable key), so there is no Clerk package in the build; without a key no sign-in UI shows and nothing loads. It exports `getToken()`, `getUser()`, `onAuthChange()`, `openSignIn()`, `isConfigured()`; the header pill is a Sign in button or Clerk's own user button. The key is read at build time from `VITE_CLERK_PUBLISHABLE_KEY` or `NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY` (the name Clerk's Vercel Marketplace install adds; `vite.config.js` `envPrefix` lets it through). Server side, `api/_account.js` verifies the Clerk session token with `@clerk/backend` `verifyToken` (`CLERK_SECRET_KEY`, or `CLERK_JWT_KEY` for a networkless check) and keeps plans and credit counts in Neon Postgres through `@neondatabase/serverless` (`DATABASE_URL` or `POSTGRES_URL`). The schema is `api/_account-schema.js` (`subscriptions`, `ai_usage`, and the atomic `glint_use_credits(user, cost, free_limit, pro_limit)` function, keyed by Clerk's text user id); **the server installs it itself** the first time a query fails with a missing function or table, so there is no SQL to run by hand. `metered(kind, handler)` wraps the six hosted AI routes, spends credits before the model call (`CREDIT_COSTS`: 1 for text / vision / enhance / agent, 5 for an image) and refunds them when the route answers with an error. It answers `401 { code: 'sign_in' }` or `402 { code: 'no_credits' }`; a Clerk or database failure answers 503 (closed, not free). **Metering is on only when the deployment has a Clerk key and a database URL**; without them the routes behave as before. Limits default to 20 free and 500 Pro credits a month (`AI_FREE_CREDITS`, `AI_PRO_CREDITS`). `api/account.js` is one function for every account route (`?op=me` today; checkout, portal and the payment webhook go here, not in new files). In the editor, `src/features/account.js` `hostedFetch(path, body)` is the only way to call a hosted AI route: it adds the token, turns a sign-in or out-of-credits answer into a 501 (which every caller already treats as "use the person's own key") and shows why in a toast unless the person has their own key; the `#ai-credits` header chip shows credits left and opens the account panel (`src/features/account-panel.js`, `openAccountPanel()`, Cmd-K `account-open`: a native `<dialog>` with the plan, credits left, what each request costs, the Pro waitlist link, Manage account and Sign out; it reads `account.js` `getAccount()` and redraws on `onAccountChange`; checkout and billing buttons go in its Pro box). **A new hosted AI route must be wrapped in `metered()` and called through `hostedFetch()`.** Tests use `ACCOUNT_STORE=memory` and sign throwaway Clerk-shaped tokens. Still to build: checkout + webhook (a merchant of record such as Lemon Squeezy), share link perks, real prices.

- **Waitlist.** The pricing page's Pro card (`pricing/index.html`, `#pro`) has a `form[data-waitlist]` that `public/site.js` (0a) posts to `/api/waitlist`. `api/_waitlist.js` holds both routes as ops of the one share function (`vercel.json` rewrites `/api/waitlist` and `/api/waitlist-export` to `api/share.js`). The Blob store is public, so entries are stored unreadable: the file name is an HMAC of the email (which also de-duplicates) and the body is AES-256-GCM encrypted, both keyed from `SHARE_SIGNING_SECRET`. Changing that secret orphans the list. The join route answers the same whether or not the email was already there. Read the list with `curl -H "Authorization: Bearer $CRON_SECRET" https://<site>/api/waitlist-export?format=csv`.
- **Analytics.** Vercel Web Analytics, no cookies. Marketing pages load it from `public/site.js` (0) (skipped on localhost) and send `open_studio` and `waitlist_join`. The editor uses `src/features/analytics.js` (`bindAnalytics()`, `track(name, data)`): `section_used` once per sidebar section per visit (a capture listener, so new sections are covered for free), `export`, `share_link`, `roll_develop`, `ai_blocked` (sign-in needed or out of credits). **Events carry feature names and choices only, never images, file names, colors or typed text;** if you add an event, list it on the privacy page.
Expand Down
2 changes: 1 addition & 1 deletion api/_account.js
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ export async function me(req, res) {
if (req.method !== 'GET') throw new ApiError(405, 'Method not allowed');
const cfg = accountConfig();
if (!cfg.enabled) { res.status(200).json({ enabled: false }); return; }
const base = { enabled: true, hosted: Boolean(serverOpenAIKey()), costs: CREDIT_COSTS, freeCredits: cfg.freeCredits };
const base = { enabled: true, hosted: Boolean(serverOpenAIKey()), costs: CREDIT_COSTS, freeCredits: cfg.freeCredits, proCredits: cfg.proCredits };
const user = await userFromToken(cfg, readBearer(req));
if (!user) { res.status(200).json({ ...base, signedIn: false }); return; }
const usage = await useCredits(cfg, user.id, 0);
Expand Down
52 changes: 52 additions & 0 deletions docs/GLINT-PRO-STATUS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# Glint Pro: where things stand

A running note so the work can be picked up in any session. Architecture is in
`CLAUDE.md` ("Glint Pro groundwork") and `docs/BACKEND.md`; this file is only
the status and the next steps.

## Done and live on main

- Pricing page has a "Glint Pro, coming soon" card with an email waitlist
(PR #32). Read the list with the `CRON_SECRET` bearer on
`/api/waitlist-export?format=csv`.
- Usage analytics on the site and in the editor (PR #32).
- Accounts and hosted AI credits, on Clerk (sign-in) and Neon (database).
Supabase, cloud sync, the community gallery and live collaboration are
removed (PR #34).
- Deployment settings: `CRON_SECRET` is set. Neon is connected as the store
"glint-db", which added `DATABASE_URL` for Production and Preview. Clerk is
connected too (see below).

## Sign-in and metering: on and checked on the live site

- Clerk is connected as "glint-signin" with a production instance on the
site's domain (`clerk.` and `accounts.` subdomains plus three mail records,
added to the domain's DNS). `CLERK_SECRET_KEY` and
`NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY` are set for Production and Preview.
- Checked against the real Clerk and Neon: the editor shows Sign in, a new
account gets 20 credits (the schema installed itself), a Design Agent step
takes the chip to 19, and a signed-out hosted AI call answers `sign_in`.
- A browser with its own API key saved never spends credits (by design), so
test metering in a private window.
- Clerk's deployment check on Vercel is required: a production deploy waits
until Clerk's DNS and certificates are ready.
- Small leftover: the sign-in box says "glint-signin"; rename the application
to Glint in Clerk's settings.

## Next

- Checkout and webhook with a merchant of record (Lemon Squeezy was the pick),
as new ops in `api/account.js`.
- Vercel Pro plan before charging anyone (Hobby is non-commercial).
- The account panel is built (click the credits chip, or Cmd-K "Account"):
plan, credits left, costs, waitlist link, manage account, sign out. Add the
Upgrade and Manage billing buttons to it when checkout exists.
- Share link perks for Pro, then real prices on the pricing page.
- Watch whether 20 free credits is enough: the Design Agent spends one per
step. Tune with `AI_FREE_CREDITS`.

## Decisions made

- The studio stays free; Pro covers the parts that cost money to run.
- Starting numbers: about $8 a month, 20 free and 500 Pro credits.
- Glint Pro will be its own numbered release (v42 Junction shipped separately).
2 changes: 1 addition & 1 deletion editor/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
<span>Glint <span style="font-size:13px;font-weight:400;color:var(--text-secondary);">v42 · Junction</span></span>
</div>
<div class="header-actions">
<span id="ai-credits" class="account-pill" style="display:none;"></span>
<button type="button" id="ai-credits" class="account-pill" style="display:none;"></button>
<span id="auth-pill" style="display:inline-flex;gap:6px;align-items:center;margin-right:4px;"></span>
<div class="ui-mode-toggle" id="ui-mode-toggle" role="group" aria-label="Interface mode">
<button type="button" data-mode="simple" title="Simple mode: just the essential tools">Simple</button>
Expand Down
1 change: 1 addition & 0 deletions scripts/regression-tests.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -1388,6 +1388,7 @@ async function testHostedAiIsMetered() {

const me = await callRoute(accountRouter, shareReq('GET', null, { query: { op: 'me' }, headers: { authorization: `Bearer ${good}` } }));
assert.equal(me.body.signedIn, true);
assert.equal(me.body.proCredits, 40, 'the account route tells the panel what Pro gives');
assert.deepEqual([me.body.plan, me.body.used, me.body.limit], ['free', 3, 3]);
assert.equal((await callRoute(accountRouter, shareReq('GET', null, { query: { op: 'me' } }))).body.signedIn, false);
assert.equal((await callRoute(accountRouter, shareReq('GET', null, { query: { op: 'constructor' } }))).statusCode, 404);
Expand Down
161 changes: 161 additions & 0 deletions src/features/account-panel.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
// Glint Pro groundwork: the account panel. One place for the plan, the hosted
// AI credits left this month and what Pro will add. It opens from the credits
// chip in the header and from Cmd-K. Checkout and "manage billing" buttons go
// here once they exist. Everything is built with textContent; nothing from the
// server or from Clerk is rendered as HTML.
import { getUser, isConfigured, openSignIn, openUserProfile, signOut, onAuthChange } from './auth.js';
import { getAccount, onAccountChange, refreshAccount, hasOwnKey, resetDay } from './account.js';

let dlg = null;
let body = null;

function node(tag, className, text) {
const n = document.createElement(tag);
if (className) n.className = className;
if (text != null) n.textContent = text;
return n;
}

function button(label, className, run) {
const b = node('button', `btn ${className}`, label);
b.type = 'button';
b.addEventListener('click', run);
return b;
}

function build() {
dlg = node('dialog', 'glint-dialog account-panel');
dlg.setAttribute('aria-labelledby', 'account-panel-title');
const head = node('div', 'account-head');
const title = node('h3', '', 'Your account');
title.id = 'account-panel-title';
const close = node('button', 'account-close', '✕');
close.type = 'button';
close.title = 'Close';
close.addEventListener('click', () => dlg.close());
head.append(title, close);
body = node('div', 'account-body');
dlg.append(head, body);
document.body.appendChild(dlg);
// Keys stay inside, so the editor's shortcuts never act behind the panel.
dlg.addEventListener('keydown', (e) => e.stopPropagation());
dlg.addEventListener('click', (e) => { if (e.target === dlg) dlg.close(); });
}

function costLine(costs) {
const one = costs.text || 1;
const image = costs.image || 5;
const credits = (n) => `${n} credit${n === 1 ? '' : 's'}`;
return `A text or vision request, an enhance or one Design Agent step uses ${credits(one)}. An AI image uses ${credits(image)}.`;
}

function creditsBox(usage, offer) {
const box = node('div', 'account-box');
const left = Math.max(0, usage.limit - usage.used);
const count = node('div', 'account-count');
count.append(node('strong', '', String(left)), node('span', '', `of ${usage.limit} hosted AI credits left this month`));
const bar = node('div', 'account-bar');
bar.setAttribute('role', 'img');
bar.setAttribute('aria-label', `${left} of ${usage.limit} credits left`);
const fill = node('i');
fill.style.width = `${usage.limit > 0 ? Math.round((left / usage.limit) * 100) : 0}%`;
bar.append(fill);
box.append(count, bar);
const day = usage.resets ? resetDay(usage.resets) : '';
if (day) box.append(node('p', 'account-note', `They start over on ${day}.`));
box.append(node('p', 'account-note', costLine((offer && offer.costs) || {})));
if (hasOwnKey()) {
box.append(node('p', 'account-note', 'This browser has your own API key saved, so AI features use that key and spend no credits.'));
} else if (left === 0) {
box.append(node('p', 'account-note', 'Out of credits? Your own API key (AI settings) works without any.'));
}
return box;
}

function proBox(usage, offer) {
const box = node('div', 'account-box');
if (usage && usage.plan === 'pro') {
box.append(node('h4', '', 'You are on Glint Pro'), node('p', 'account-note', 'Thank you for backing Glint. Billing controls will show up here.'));
return box;
}
const pro = offer && offer.proCredits;
box.append(
node('h4', '', 'Glint Pro is coming'),
node('p', 'account-note', `${pro ? `${pro} hosted AI credits a month` : 'More hosted AI credits'} and share links that last. The studio itself stays free.`),
);
const link = node('a', 'btn btn-primary', 'Join the waitlist');
link.href = '/pricing/#pro';
link.target = '_blank';
link.rel = 'noopener';
box.append(link);
return box;
}

function render() {
if (!dlg || !dlg.open) return;
const user = getUser();
const { usage, offer, loadFailed } = getAccount();
const parts = [];

if (!isConfigured()) {
parts.push(node('p', 'account-note', 'Accounts are not set up on this copy of Glint. Everything in the studio works without one, and AI features use your own API key.'));
} else if (!user) {
const free = offer && offer.freeCredits;
const box = node('div', 'account-box');
box.append(
node('h4', '', 'Sign in for free AI credits'),
node('p', 'account-note', `A free account gives you ${free || 'a set of'} hosted AI credits every month. The studio needs no account, and neither does your own API key.`),
button('Sign in', 'btn-primary', () => { dlg.close(); openSignIn(); }),
);
parts.push(box, proBox(null, offer));
} else {
const who = node('div', 'account-who');
const text = node('div', 'account-who-text');
text.append(node('div', 'account-name', user.name));
if (user.email && user.email !== user.name) text.append(node('div', 'account-email', user.email));
const isPro = Boolean(usage && usage.plan === 'pro');
who.append(text, node('span', `account-plan${isPro ? ' is-pro' : ''}`, isPro ? 'Glint Pro' : 'Free'));
parts.push(who);

if (usage) {
parts.push(creditsBox(usage, offer));
} else {
const box = node('div', 'account-box');
if (loadFailed) {
box.append(node('p', 'account-note', 'Your credits could not be loaded. Check your connection and try again.'), button('Try again', 'btn-secondary', () => refreshAccount()));
} else if (offer && !offer.hosted) {
box.append(node('p', 'account-note', 'Hosted AI is off on this copy of Glint, so there are no credits to count. AI features use your own API key.'));
} else {
box.append(node('p', 'account-note', 'Loading your credits...'));
}
parts.push(box);
}
parts.push(proBox(usage, offer));

const actions = node('div', 'account-actions');
actions.append(
button('Manage account', 'btn-secondary', () => { dlg.close(); openUserProfile(); }),
button('Sign out', 'btn-secondary', async () => { dlg.close(); await signOut(); }),
);
parts.push(actions);
}
// Keep focus where it was when a refresh redraws the panel under the reader.
const hadFocus = body.contains(document.activeElement);
body.replaceChildren(...parts);
if (hadFocus) dlg.querySelector('.account-close').focus();
}

export function openAccountPanel() {
if (!dlg) build();
if (!dlg.open) dlg.showModal();
render();
// The chip can be a little behind (another tab, another device).
if (isConfigured()) refreshAccount();
}

export function bindAccountPanel() {
const chip = document.getElementById('ai-credits');
if (chip) chip.addEventListener('click', openAccountPanel);
onAccountChange(render);
onAuthChange(render);
}
Loading
Loading