Open History to see the last commit
1import {
2 createRealtimeClient,
3 type MaterializedLiveQuerySubscription,
4 type SealedLiveQuery,
5} from "@neon/realtime/client";
6import { useSyncExternalStore } from "react";
7import { COLORS } from "../shared/catalogue";
8import type {
9 World,
10 Part,
11 Connection,
12 Viewer,
13 SceneRow,
14 Preview,
15 Position,
16 Edit,
17 Receipt,
18 AIConversationRow,
19 Member,
20} from "../shared/types";
21import {
22 openLiveQuery,
23 type QueryState,
24 type QuerySnapshot,
25} from "./live-query";
26import { sceneEntity } from "../shared/types";
27type Pending = {
28 id: string;
29 generation: number;
30 parts: Part[];
31 receipt?: Receipt;
32};
33type State = {
34 world: World | null;
35 parts: Part[];
36 connections: Connection[];
37 viewers: Viewer[];
38 status: string;
39 error: string | null;
40 guest: string;
41 name: string;
42 color: string;
43 canReset: boolean;
44 canBuildAI: boolean;
45 role: string | null;
46 queries: Record<"presence" | "history" | "member", QueryState>;
47 pending: Pending[];
48 history: { undo: string | null; redo: string | null };
49 lastTx: string | null;
50 serverOffset: number;
51};
52let state: State = {
53 world: null,
54 parts: [],
55 connections: [],
56 viewers: [],
57 status: "connecting",
58 error: null,
59 guest: "",
60 name: "",
61 color: COLORS[0].hex,
62 canReset: false,
63 canBuildAI: false,
64 role: null,
65 queries: {
66 presence: { status: "connecting" },
67 history: { status: "connecting" },
68 member: { status: "connecting" },
69 },
70 pending: [],
71 history: { undo: null, redo: null },
72 lastTx: null,
73 serverOffset: 0,
74};
75const listeners = new Set<() => void>();
76export const getState = () => state;
77function publish(patch: Partial<State>) {
78 state = { ...state, ...patch };
79 listeners.forEach((fn) => fn());
80}
81export function useWorkshop() {
82 return useSyncExternalStore((fn) => {
83 listeners.add(fn);
84 return () => {
85 listeners.delete(fn);
86 };
87 }, getState);
88}
89const API = (import.meta.env.VITE_API_URL || "").replace(/\/$/, "");
90let token = sessionStorage.getItem("neon-bricks-session") || "";
91let viewer = "",
92 sequence = 0,
93 client: ReturnType<typeof createRealtimeClient> | undefined,
94 scene: MaterializedLiveQuerySubscription<SceneRow> | undefined;
95let startAbort: AbortController | undefined;
96let disposed = false,
97 epoch = 0,
98 subscriptions = new Set<() => void>(),
99 heartTimer: ReturnType<typeof setInterval> | undefined,
100 sessionTimer: ReturnType<typeof setInterval> | undefined;
101let clock = { server: Date.now(), mono: performance.now() };
102export const serverNow = () => clock.server + performance.now() - clock.mono;
103export const getViewerId = () => viewer;
104let rejoining = false;
105let liveHistory:
106 { undo: string | null; redo: string | null; generation: number } | undefined;
107let intent: {
108 preview: Preview | null;
109 selection: string[];
110 cursor: Position | null;
111 } = {
112 preview: null,
113 selection: [],
114 cursor: null,
115 },
116 lastIntent = "",
117 lastSample = 0,
118 presenceTimer: ReturnType<typeof setTimeout> | undefined,
119 presenceFlight: number | null = null;
120export async function api<T>(path: string, init: RequestInit = {}): Promise<T> {
121 const sent = performance.now(),
122 response = await fetch(`${API}/api${path}`, {
123 ...init,
124 headers: {
125 "Content-Type": "application/json",
126 ...(token ? { Authorization: `Bearer ${token}` } : {}),
127 ...init.headers,
128 },
129 signal: init.signal
130 ? AbortSignal.any([init.signal, AbortSignal.timeout(20_000)])
131 : AbortSignal.timeout(20_000),
132 });
133 const data = await response.json();
134 if (!response.ok) {
135 const e = new Error(
136 data.error || `Request failed (${response.status})`,
137 ) as Error & { status: number };
138 e.status = response.status;
139 throw e;
140 }
141 const elapsed = performance.now() - sent;
142 // A long AI invocation includes inference time, not just network latency.
143 // It must not move the presence clock forward by half the generation time.
144 if (data.serverTime && elapsed < 5000) {
145 clock = {
146 server: data.serverTime + elapsed / 2,
147 mono: performance.now(),
148 };
149 publish({ serverOffset: clock.server - Date.now() });
150 }
151 return data;
152}
153export function notice(message: string | null) {
154 publish({ error: message });
155}
156export async function watchConversation(
157 world: string,
158 receive: (snapshot: QuerySnapshot<AIConversationRow>) => void,
159 signal?: AbortSignal,
160) {
161 if (!client)
162 throw new Error("Wait for the workshop to connect, then try again.");
163 const currentClient = client,
164 run = epoch;
165 const live = await openLiveQuery({
166 client: currentClient,
167 fetchQuery: (refreshSignal) =>
168 api<SealedLiveQuery<AIConversationRow>>(`/worlds/${world}/live/ai`, {
169 signal: signal
170 ? AbortSignal.any([signal, refreshSignal])
171 : refreshSignal,
172 }),
173 now: serverNow,
174 active: () =>
175 !disposed &&
176 run === epoch &&
177 client === currentClient &&
178 !signal?.aborted,
179 receive,
180 });
181 const stop = () => {
182 live.stop();
183 subscriptions.delete(stop);
184 signal?.removeEventListener("abort", stop);
185 };
186 subscriptions.add(stop);
187 signal?.addEventListener("abort", stop, { once: true });
188 if (signal?.aborted) stop();
189 return stop;
190}
191export async function start(slug: string) {
192 startAbort?.abort();
193 const abort = new AbortController();
194 startAbort = abort;
195 subscriptions.forEach((off) => off());
196 subscriptions.clear();
197 client?.close();
198 clearInterval(heartTimer);
199 clearInterval(sessionTimer);
200 publish({
201 status: "connecting",
202 error: null,
203 role: null,
204 canBuildAI: false,
205 canReset: false,
206 history: { undo: null, redo: null },
207 pending: [],
208 viewers: [],
209 parts: [],
210 connections: [],
211 queries: {
212 presence: { status: "connecting" },
213 history: { status: "connecting" },
214 member: { status: "connecting" },
215 },
216 });
217 disposed = false;
218 const run = ++epoch,
219 active = () => !disposed && run === epoch;
220 clearTimeout(presenceTimer);
221 presenceTimer = undefined;
222 presenceFlight = null;
223 sequence = 0;
224 liveHistory = undefined;
225 lastIntent = "";
226 intent = { preview: null, selection: [], cursor: null };
227 try {
228 if (!token) {
229 const name = `Builder ${Math.floor(Math.random() * 900 + 100)}`,
230 color = COLORS[Math.floor(Math.random() * 6)].hex;
231 const session = await api<{ token: string }>("/session", {
232 method: "POST",
233 body: JSON.stringify({ name, color }),
234 signal: abort.signal,
235 });
236 if (!active()) return;
237 token = session.token;
238 sessionStorage.setItem("neon-bricks-session", token);
239 }
240 let joined: any;
241 try {
242 joined = await api(`/worlds/${slug}/join`, {
243 method: "POST",
244 signal: abort.signal,
245 });
246 } catch (e) {
247 if (!active()) return;
248 if ((e as any).status === 401) {
249 token = "";
250 sessionStorage.removeItem("neon-bricks-session");
251 return start(slug);
252 }
253 throw e;
254 }
255 if (!active()) return;
256 viewer = joined.viewer;
257 publish({
258 world: joined.world,
259 guest: joined.guest,
260 name: joined.name,
261 color: joined.color,
262 // Permissions are enabled only after live member metadata arrives.
263 });
264 const url = import.meta.env.VITE_NEON_REALTIME_URL;
265 if (!url) throw new Error("Realtime URL is missing. Check .env.local.");
266 client = createRealtimeClient({ url });
267 const subscribe = async <T>(
268 kind: string,
269 receive: (data: readonly T[], status: string, error?: string) => void,
270 ) => {
271 try {
272 const live = await openLiveQuery({
273 client: client!,
274 fetchQuery: (signal) =>
275 api<SealedLiveQuery<T>>(`/worlds/${joined.world.id}/live/${kind}`, {
276 signal: AbortSignal.any([signal, abort.signal]),
277 }),
278 now: serverNow,
279 active,
280 receive: ({ data, status, error }) => receive(data, status, error),
281 });
282 subscriptions.add(live.stop);
283 return live.sub;
284 } catch (error) {
285 if (active()) receive([], "error", (error as Error).message);
286 return undefined;
287 }
288 };
289 const sceneSubscription = await subscribe<SceneRow>(
290 "scene",
291 (rows, status, error) => {
292 const headerRow = rows.find((r) => r.kind === "world"),
293 header = headerRow ? (sceneEntity(headerRow) as World) : undefined;
294 const parts = rows
295 .filter((r) => r.kind === "part")
296 .map((r) => sceneEntity(r) as Part),
297 connections = rows
298 .filter((r) => r.kind === "connection")
299 .map((r) => sceneEntity(r) as Connection);
300 if (
301 header &&
302 state.world &&
303 header.generation !== state.world.generation
304 ) {
305 intent = { preview: null, selection: [], cursor: null };
306 lastIntent = "";
307 publish({ pending: [], history: { undo: null, redo: null } });
308 }
309 const pending = state.pending.filter(
310 (p) =>
311 !p.receipt?.accepted ||
312 !p.parts.every((part) =>
313 part.deleted
314 ? !parts.some((x) => x.id === part.id)
315 : parts.some(
316 (x) => x.id === part.id && x.revision >= part.revision,
317 ),
318 ),
319 );
320 if (status === "live" && !header) {
321 publish({
322 parts: [],
323 connections: [],
324 pending: [],
325 status: "error",
326 error: "Workshop access ended. Reload to rejoin.",
327 });
328 return;
329 }
330 publish({
331 ...(header ? { world: header } : {}),
332 parts,
333 connections,
334 pending,
335 ...(status === "live" && header
336 ? {
337 history:
338 liveHistory?.generation === header.generation
339 ? { undo: liveHistory.undo, redo: liveHistory.redo }
340 : { undo: null, redo: null },
341 }
342 : {}),
343 status,
344 ...(error
345 ? { error }
346 : status === "live" && state.status !== "live"
347 ? { error: null }
348 : {}),
349 });
350 },
351 );
352 if (!active()) return;
353 scene = sceneSubscription;
354 const queryState = (
355 kind: "presence" | "history" | "member",
356 status: string,
357 error?: string,
358 ) => ({
359 ...state.queries,
360 [kind]: { status, error },
361 });
362 const presenceSubscription = subscribe<Viewer>(
363 "presence",
364 (rows, status, error) => {
365 publish({
366 queries: queryState("presence", status, error),
367 ...(status === "live" || status === "error"
368 ? { viewers: [...rows] }
369 : {}),
370 });
371 },
372 );
373 const historySubscription = subscribe<{
374 undo: string | null;
375 redo: string | null;
376 generation: number;
377 }>("history", (rows, status, error) => {
378 if (status === "live" || status === "error") liveHistory = rows[0];
379 publish({
380 queries: queryState("history", status, error),
381 ...(status === "live" || status === "error"
382 ? {
383 history:
384 rows[0] && rows[0].generation === state.world?.generation
385 ? { undo: rows[0].undo, redo: rows[0].redo }
386 : { undo: null, redo: null },
387 }
388 : {}),
389 });
390 });
391 const memberSubscription = subscribe<Member>(
392 "member",
393 (rows, status, error) => {
394 const member = rows[0];
395 publish({
396 queries: queryState("member", status, error),
397 ...(status === "live"
398 ? {
399 name: member?.name || "",
400 color: member?.color || COLORS[0].hex,
401 role: member?.role || null,
402 }
403 : {}),
404 canBuildAI: status === "live" && member?.role === "editor",
405 canReset: status === "live" && member?.can_reset === true,
406 });
407 },
408 );
409 if (!active()) return;
410 heartTimer = setInterval(() => {
411 if (document.visibilityState === "visible") void sendPresence(false);
412 }, 10_000);
413 sessionTimer = setInterval(() => {
414 if (document.visibilityState === "visible")
415 void api("/session/renew", { method: "POST" }).catch((e) =>
416 publish({ status: "error", error: e.message }),
417 );
418 }, 5 * 60_000);
419 await sendPresence(false);
420 await Promise.all([
421 presenceSubscription,
422 historySubscription,
423 memberSubscription,
424 ]);
425 } catch (e) {
426 if (active()) publish({ status: "error", error: (e as Error).message });
427 }
428}
429export function stop() {
430 startAbort?.abort();
431 disposed = true;
432 ++epoch;
433 subscriptions.forEach((off) => off());
434 subscriptions.clear();
435 clearInterval(heartTimer);
436 clearInterval(sessionTimer);
437 clearTimeout(presenceTimer);
438 presenceTimer = undefined;
439 client?.close();
440 client = undefined;
441 scene = undefined;
442 if (viewer && state.world)
443 void api(`/worlds/${state.world.id}/viewers/${viewer}`, {
444 method: "DELETE",
445 }).catch(() => {});
446}
447export function setIntent(preview: Preview | null, selection: string[]) {
448 intent = { ...intent, preview, selection };
449 queuePresence();
450}
451export function setCursor(cursor: Position | null) {
452 intent = { ...intent, cursor };
453 queuePresence();
454}
455function queuePresence(delay = 0) {
456 if (
457 disposed ||
458 state.status === "error" ||
459 presenceTimer ||
460 presenceFlight === epoch
461 )
462 return;
463 presenceTimer = setTimeout(
464 () => {
465 presenceTimer = undefined;
466 void sendPresence(true);
467 },
468 Math.max(delay, 200 - (performance.now() - lastSample)),
469 );
470}
471export async function sendPresence(sample: boolean) {
472 if (
473 !viewer ||
474 !state.world ||
475 state.world.status !== "open" ||
476 state.status === "error" ||
477 disposed ||
478 presenceFlight === epoch
479 )
480 return;
481 const current = JSON.stringify(intent),
482 now = performance.now();
483 if (sample && now - lastSample < 200) {
484 queuePresence(200 - (now - lastSample));
485 return;
486 }
487 if (
488 sample &&
489 current === lastIntent &&
490 ((!intent.preview && !intent.cursor) || now - lastSample < 1000)
491 )
492 return;
493 if (sample) {
494 lastIntent = current;
495 lastSample = now;
496 }
497 const run = epoch;
498 presenceFlight = run;
499 let failed = false;
500 try {
501 await api(`/worlds/${state.world.id}/presence`, {
502 method: "POST",
503 body: JSON.stringify({
504 viewer,
505 sequence: ++sequence,
506 generation: state.world.generation,
507 ...intent,
508 sample,
509 }),
510 });
511 } catch (e) {
512 if (disposed || run !== epoch) return;
513 failed = true;
514 if (sample) lastIntent = "";
515 if ((e as any).status === 401 || (e as any).status === 403) {
516 publish({ status: "error", error: (e as Error).message });
517 return;
518 }
519 if ((e as any).status === 410 && !rejoining) {
520 rejoining = true;
521 try {
522 const joined = await api<any>(`/worlds/${state.world.slug}/join`, {
523 method: "POST",
524 });
525 if (disposed || run !== epoch) return;
526 viewer = joined.viewer;
527 sequence = 0;
528 lastIntent = "";
529 } catch (error) {
530 publish({ status: "stale", error: (error as Error).message });
531 } finally {
532 rejoining = false;
533 }
534 }
535 } finally {
536 if (run === epoch) {
537 presenceFlight = null;
538 // Only the newest pointer position waits behind a slow request.
539 if (JSON.stringify(intent) !== lastIntent)
540 queuePresence(failed ? 1000 : 0);
541 }
542 }
543}
544export function displayParts() {
545 const map = new Map(state.parts.map((p) => [p.id, p]));
546 for (const p of state.pending.flatMap((p) => p.parts)) {
547 if (p.deleted) map.delete(p.id);
548 else map.set(p.id, p);
549 }
550 return [...map.values()];
551}
552export async function submit(
553 request: Omit<Edit, "operationId" | "generation">,
554) {
555 if (
556 !state.world ||
557 state.world.status !== "open" ||
558 state.status !== "live" ||
559 state.queries.member.status !== "live" ||
560 state.role !== "editor" ||
561 (request.action !== "edit" && state.queries.history.status !== "live")
562 ) {
563 notice("Wait for the live connection before editing.");
564 return false;
565 }
566 const run = epoch;
567 const world = state.world,
568 edit: Edit = {
569 ...request,
570 operationId: crypto.randomUUID(),
571 generation: world.generation,
572 };
573 const touch = edit.changes?.map((c) => c.id) || [];
574 if (
575 state.pending.some((p) => p.parts.some((part) => touch.includes(part.id)))
576 ) {
577 notice("That part is still being saved.");
578 return false;
579 }
580 const optimistic = (edit.changes || [])
581 .map((change) => {
582 const old = state.parts.find((p) => p.id === change.id);
583 return { ...old, ...change, revision: (old?.revision || 0) + 1 } as Part;
584 })
585 .filter((p) => p.key && p.color && p.position);
586 publish({
587 pending: [
588 ...state.pending,
589 { id: edit.operationId, generation: world.generation, parts: optimistic },
590 ],
591 error: null,
592 });
593 let receipt: Receipt | undefined;
594 for (let i = 0; i < 3; i++)
595 try {
596 receipt = await api(`/worlds/${world.id}/edit`, {
597 method: "POST",
598 body: JSON.stringify(edit),
599 });
600 break;
601 } catch (e) {
602 if ((e as any).status && (e as any).status !== 503) {
603 notice((e as Error).message);
604 break;
605 }
606 }
607 if (!receipt) {
608 try {
609 receipt = await api<Receipt>(
610 `/worlds/${world.id}/operations/${edit.operationId}`,
611 );
612 } catch {
613 notice("Waiting for confirmation from Postgres…");
614 void recover(edit, world.id);
615 return false;
616 }
617 }
618 if (!receipt) {
619 notice("Waiting for confirmation from Postgres…");
620 void recover(edit, world.id);
621 return false;
622 }
623 if (disposed || run !== epoch) return false;
624 if (!receipt.accepted) {
625 publish({
626 pending: state.pending.filter((p) => p.id !== edit.operationId),
627 error: receipt.error || "Edit conflicted",
628 });
629 return false;
630 }
631 if (state.world?.generation !== receipt.generation) return true;
632 publish({
633 pending: state.pending.map((p) =>
634 p.id === edit.operationId
635 ? { ...p, parts: receipt!.parts || [], receipt }
636 : p,
637 ),
638 lastTx: receipt.txid || null,
639 });
640 try {
641 if (receipt.txid) await scene?.awaitTxId(receipt.txid, 5000);
642 if (disposed || run !== epoch) return true;
643 publish({
644 pending: state.pending.filter((p) => p.id !== edit.operationId),
645 });
646 } catch {
647 if (disposed || run !== epoch) return true;
648 const actual = scene?.getSnapshot();
649 if (
650 actual?.status === "live" &&
651 receipt.parts?.every((p) =>
652 p.deleted
653 ? !state.parts.some((x) => x.id === p.id)
654 : state.parts.some((x) => x.id === p.id && x.revision >= p.revision),
655 )
656 )
657 publish({
658 pending: state.pending.filter((p) => p.id !== edit.operationId),
659 });
660 else notice("Saved in Postgres; waiting for the live scene to catch up.");
661 }
662 return true;
663}
664async function recover(edit: Edit, world: string) {
665 const run = epoch;
666 for (let attempt = 0; attempt < 6; attempt++) {
667 if (
668 disposed ||
669 run !== epoch ||
670 state.world?.id !== world ||
671 state.world.generation !== edit.generation
672 )
673 return;
674 await new Promise((resolve) =>
675 setTimeout(resolve, Math.min(1000 * 2 ** attempt, 10_000)),
676 );
677 try {
678 const r = await api<Receipt>(`/worlds/${world}/edit`, {
679 method: "POST",
680 body: JSON.stringify(edit),
681 });
682 if (
683 disposed ||
684 run !== epoch ||
685 state.world?.generation !== edit.generation
686 )
687 return;
688 if (r.accepted) {
689 publish({
690 pending: state.pending.map((p) =>
691 p.id === edit.operationId
692 ? { ...p, receipt: r, parts: r.parts || [] }
693 : p,
694 ),
695 lastTx: r.txid || null,
696 });
697 try {
698 if (r.txid) await scene?.awaitTxId(r.txid, 5000);
699 } catch {}
700 if (
701 disposed ||
702 run !== epoch ||
703 state.world?.generation !== edit.generation
704 )
705 return;
706 const applied = r.parts?.every((p) =>
707 p.deleted
708 ? !state.parts.some((x) => x.id === p.id)
709 : state.parts.some(
710 (x) => x.id === p.id && x.revision >= p.revision,
711 ),
712 );
713 if (applied)
714 publish({
715 pending: state.pending.filter((p) => p.id !== edit.operationId),
716 error: null,
717 });
718 else
719 notice("Saved in Postgres; waiting for the live scene to catch up.");
720 } else
721 publish({
722 pending: state.pending.filter((p) => p.id !== edit.operationId),
723 error: r.error || "Edit conflicted",
724 });
725 return;
726 } catch {}
727 }
728 publish({
729 status: "stale",
730 error:
731 "Could not confirm the edit. Reload to recover the authoritative workshop.",
732 });
733}
734export function selectedConnections(ids: string[]) {
735 return state.connections
736 .filter((c) => ids.includes(c.a) || ids.includes(c.b))
737 .map((c) => ({ id: c.id, revision: c.revision }));
738}
739export async function newRoom(empty = false) {
740 const w = await api<{ slug: string }>("/worlds", {
741 method: "POST",
742 body: JSON.stringify({
743 title: empty ? "A blank canvas" : "My little workshop",
744 starter: empty ? "empty" : "rover",
745 }),
746 });
747 location.assign(`/w/${w.slug}`);
748}
749export async function resetRoom(empty = false) {
750 if (!state.world) return;
751 await api(`/worlds/${state.world.id}/reset`, {
752 method: "POST",
753 body: JSON.stringify({
754 generation: state.world.generation,
755 starter: empty ? "empty" : "rover",
756 }),
757 });
758}
759export async function rename(name: string) {
760 await api("/profile", {
761 method: "POST",
762 body: JSON.stringify({ name, color: state.color }),
763 });
764}
765
766export async function lifecycleRoom(status: "open" | "closed") {
767 if (!state.world) return;
768 await api(`/worlds/${state.world.id}/lifecycle`, {
769 method: "POST",
770 body: JSON.stringify({ generation: state.world.generation, status }),
771 });
772}