Open History to see the last commit
1import { randomUUID, createHash } from 'node:crypto';
2import type { PoolClient } from 'pg';
3import { ApiError, type AppSnapshot, type GlowApp, type Message, type Run, type Version } from '@glow/contracts';
4import { database, transaction } from './database.ts';
5import { config } from './config.ts';
6
7export const now = () => new Date().toISOString();
8// A readable placeholder until the agent names the app: the first clause of the prompt, trimmed at a word.
9export function titleFromPrompt(prompt: string): string {
10 const clause = prompt.replace(/^(please\s+)?(can you\s+)?(make|build|create)\s+(me\s+)?(a|an)?\s*/i, '').split(/[.!?\n:]/)[0].trim() || prompt.trim();
11 const words = clause.split(/\s+/); let title = '';
12 for (const word of words) { if ((title + ' ' + word).trim().length > 40) break; title = (title + ' ' + word).trim(); }
13 title = title || clause.slice(0, 40);
14 return title.charAt(0).toUpperCase() + title.slice(1);
15}
16export const fingerprint = (value: unknown) => createHash('sha256').update(JSON.stringify(value)).digest('hex');
17
18export async function ownedApp(appId: string, ownerId: string, client: Pick<PoolClient, 'query'> = database(), lock = false): Promise<GlowApp> {
19 const { rows } = await client.query<{ data: GlowApp }>(`SELECT data FROM glow_apps WHERE id=$1 AND owner_id=$2 AND NOT coalesce((data->>'deleted')::boolean,false)${lock ? ' FOR UPDATE' : ''}`, [appId, ownerId]);
20 if (!rows[0]) throw new ApiError(404, 'Creation not found');
21 return rows[0].data;
22}
23export async function appById(appId: string): Promise<GlowApp & { disabled?: boolean }> {
24 const { rows } = await database().query('SELECT data FROM glow_apps WHERE id=$1', [appId]);
25 if (!rows[0] || rows[0].data.disabled) throw new ApiError(404, 'This creation is unavailable');
26 return rows[0].data;
27}
28export async function appendMessage(client: Pick<PoolClient, 'query'>, appId: string, role: Message['role'], content: string, runId: string | null = null, messageId: string = randomUUID(), metadata: Pick<Message, 'kind' | 'options' | 'answeredBy' | 'answerTo'> = {}) {
29 const data = { id: messageId, appId, role, content, runId, createdAt: now(), ...metadata };
30 const inserted = await client.query('INSERT INTO glow_messages(id,app_id,data) VALUES($1,$2,$3) ON CONFLICT(id) DO NOTHING RETURNING id', [messageId, appId, JSON.stringify(data)]);
31 if (!inserted.rowCount) throw new ApiError(409, 'Message ID already used');
32 return data;
33}
34export async function acceptMessage(client: PoolClient, app: GlowApp, prompt: string, operationId: string) {
35 const previous = await client.query<{ data: Run; prompt: string }>(`SELECT r.data,m.data->>'content' AS prompt FROM glow_runs r JOIN glow_messages m ON m.id=(r.data->>'messageId')::uuid WHERE r.operation_id=$1`, [operationId]);
36 if (previous.rows[0]) {
37 if (previous.rows[0].data.appId !== app.id || previous.rows[0].prompt !== prompt) throw new ApiError(409, 'Request ID already used');
38 return previous.rows[0].data;
39 }
40 const count = await client.query('SELECT count(*)::int AS count FROM glow_runs WHERE app_id=$1 AND data->>\'status\' IN (\'queued\',\'running\',\'stopping\')', [app.id]);
41 if (count.rows[0].count >= 5) throw new ApiError(429, 'Let a few changes finish before adding more.');
42 const runId = randomUUID(), messageId = operationId;
43 const run: Run = { id: runId, appId: app.id, messageId, status: 'queued', phase: 'Queued', generation: app.generation, attempt: 0, fence: 0, error: null, createdAt: now(), updatedAt: now() };
44 await appendMessage(client, app.id, 'user', prompt, runId, messageId);
45 await client.query('INSERT INTO glow_runs(id,app_id,operation_id,data) VALUES($1,$2,$3,$4)', [runId, app.id, operationId, JSON.stringify({ ...run, agentVersion: config().agentVersion })]);
46 return run;
47}
48export async function snapshot(appId: string, ownerId: string): Promise<AppSnapshot> {
49 const app = await ownedApp(appId, ownerId);
50 const [messages, runs, versions] = await Promise.all([
51 database().query('SELECT data || jsonb_build_object(\'sequence\',sequence) AS data FROM glow_messages WHERE app_id=$1 ORDER BY sequence DESC LIMIT 100', [appId]),
52 database().query('SELECT data FROM glow_runs WHERE app_id=$1 ORDER BY data->>\'createdAt\' DESC LIMIT 30', [appId]),
53 database().query('SELECT data FROM glow_versions WHERE app_id=$1 ORDER BY data->>\'createdAt\' DESC LIMIT 30', [appId]),
54 ]);
55 return { app, messages: messages.rows.map(row => row.data).reverse(), runs: runs.rows.map(row => row.data), versions: versions.rows.map(row => row.data) };
56}
57// Deleting removes the app everywhere and erases its private chat, history, and social activity.
58// Remixes other people made stay (they are their own apps on their own branches), and the app's
59// Neon project/branch is retained because remix branches can depend on it.
60export async function deleteApp(appId: string, ownerId: string) {
61 return transaction(async client => {
62 const app = await ownedApp(appId, ownerId, client, true);
63 await client.query(`UPDATE glow_runs SET data=data || jsonb_build_object('status','superseded','fence',(data->>'fence')::int+1,'updatedAt',$2::text),owner_id=NULL,lease_until=NULL WHERE app_id=$1 AND data->>'status' IN ('queued','running','stopping','waiting')`, [app.id, now()]);
64 for (const table of ['glow_messages', 'glow_comments', 'glow_likes', 'glow_plays', 'glow_capture_jobs', 'glow_state', 'glow_state_receipts', 'glow_state_signals']) await client.query(`DELETE FROM ${table} WHERE app_id=$1`, [app.id]);
65 await client.query(`UPDATE glow_profiles SET pinned_app_id=NULL WHERE pinned_app_id=$1`, [app.id]);
66 const deleted = { ...app, deleted: true, disabled: true, visibility: 'private' as const, caption: undefined, cover: undefined, publicCover: undefined, deletedAt: now(), updatedAt: now() };
67 await client.query('UPDATE glow_apps SET data=$2 WHERE id=$1', [app.id, JSON.stringify(deleted)]);
68 return { id: app.id, deleted: true };
69 });
70}
71export async function createApp(ownerId: string, prompt: string, operationId: string, source?: { app: GlowApp; version: Version; objectKey: string }) {
72 return transaction(async client => {
73 await client.query('SELECT pg_advisory_xact_lock(hashtextextended($1,0))', [ownerId]);
74 const previous = await client.query('SELECT * FROM glow_operations WHERE id=$1', [operationId]);
75 const digest = fingerprint({ prompt, parent: source?.app.id, version: source?.version.id });
76 if (previous.rows[0]) {
77 if (previous.rows[0].owner_id !== ownerId || previous.rows[0].result.fingerprint !== digest) throw new ApiError(409, 'Request ID already used');
78 return ownedApp(previous.rows[0].result.appId, ownerId, client);
79 }
80 const app: GlowApp = {
81 id: randomUUID(), ownerId, title: source ? `Remix of ${source.app.title}`.slice(0, 48) : titleFromPrompt(prompt), titleSource: 'prompt', visibility: 'private', status: 'provisioning',
82 ...(source ? { emoji: source.app.emoji, color: source.app.color, tagline: source.app.tagline } : {}),
83 projectId: null, branchId: null, parentAppId: source?.app.id ?? null, parentVersionId: source?.version.id ?? null,
84 headVersionId: null, draftVersionId: null, generation: 0, createdAt: now(), updatedAt: now(),
85 };
86 await client.query('INSERT INTO glow_apps(id,owner_id,data) VALUES($1,$2,$3)', [app.id, ownerId, JSON.stringify(app)]);
87 if (source) {
88 const version = { ...source.version, id: randomUUID(), appId: app.id, parentId: null, published: false, summary: `Remixed ${source.app.title}`, createdAt: now() };
89 await client.query('INSERT INTO glow_versions(id,app_id,data,object_key) VALUES($1,$2,$3,$4)', [version.id, app.id, JSON.stringify(version), source.objectKey]);
90 app.draftVersionId = version.id;
91 const media = (source.version as Version).media;
92 if (media) app.cover = { versionId: version.id, poster: media.poster, clip: media.clip, color: media.color };
93 await client.query('UPDATE glow_apps SET data=$2 WHERE id=$1', [app.id, JSON.stringify(app)]);
94 await appendMessage(client, app.id, 'assistant', `Remixed ${source.app.title}. Describe what you want to change.`);
95 } else await acceptMessage(client, app, prompt, operationId);
96 await client.query('INSERT INTO glow_operations(id,owner_id,kind,result) VALUES($1,$2,\'create\',$3)', [operationId, ownerId, JSON.stringify({ appId: app.id, fingerprint: digest })]);
97 return app;
98 });
99}