Open History to see the last commit
1import { createGeneration } from "../src/server/ai";
2import { authenticate, DomainError } from "../src/server/auth";
3import assert from "node:assert/strict";
4import { randomUUID } from "node:crypto";
5import "./node-websocket";
6import { createRealtimeClient } from "@neon/realtime/client";
7import { pool } from "../src/server/db";
8import { recordDrawing } from "../src/server/ai";
9import { compileBlueprint } from "../src/shared/blueprint";
10import type { AIGeneration, AIConversationRow } from "../src/shared/types";
11const base = process.env.VITE_API_URL!.replace(/\/$/, "");
12const ids: string[] = [];
13let world: string | undefined;
14const client = createRealtimeClient({
15 url: process.env.VITE_NEON_REALTIME_URL!,
16});
17async function request(token: string, path: string, body?: unknown) {
18 if (path === "/ai/generations" && body && true) {
19 try {
20 return {
21 status: 201,
22 data: await createGeneration(
23 await authenticate(`Bearer ${token}`),
24 body as Parameters<typeof createGeneration>[1],
25 { dispatch: false },
26 ),
27 };
28 } catch (error) {
29 if (error instanceof DomainError)
30 return { status: error.status, data: { error: error.message } };
31 throw error;
32 }
33 }
34 const res = await fetch(`${base}/api${path}`, {
35 method: body === undefined ? "GET" : "POST",
36 headers: {
37 "Content-Type": "application/json",
38 ...(token ? { Authorization: `Bearer ${token}` } : {}),
39 },
40 ...(body === undefined ? {} : { body: JSON.stringify(body) }),
41 signal: AbortSignal.timeout(20000),
42 });
43 return { status: res.status, data: await res.json() };
44}
45async function ok(token: string, path: string, body?: unknown) {
46 const result = await request(token, path, body);
47 assert.ok(
48 result.status < 300,
49 `${path}: ${result.status}: ${result.data.error}`,
50 );
51 return result.data;
52}
53async function ready(id: string, blueprint: unknown) {
54 await pool.query(
55 "UPDATE ai_generations SET status='ready',blueprint=$2::jsonb,preview=$3::jsonb,preview_version=preview_version+1,lease_until=NULL,updated_at=clock_timestamp() WHERE id=$1",
56 [
57 id,
58 JSON.stringify(blueprint),
59 JSON.stringify({
60 parts: compileBlueprint(blueprint).parts,
61 title: "AI chat fixture",
62 }),
63 ],
64 );
65}
66async function parts() {
67 return (
68 await pool.query(
69 "SELECT id,key,color,revision FROM part_instances WHERE world=$1 AND deleted=0 ORDER BY id",
70 [world],
71 )
72 ).rows;
73}
74const fixture = {
75 version: 1,
76 catalogue: "workshop-1",
77 title: "AI chat fixture",
78 summary: "A small tower.",
79 parts: [
80 {
81 id: "floor",
82 part: "plate-4x4",
83 colour: "sand",
84 at: [-2, 0, -2],
85 turn: 0,
86 attach: null,
87 },
88 {
89 id: "body",
90 part: "brick-2x2",
91 colour: "jade",
92 at: [-1, 1, -1],
93 turn: 0,
94 attach: null,
95 },
96 {
97 id: "cap",
98 part: "slope-2x2",
99 colour: "poppy",
100 at: [-1, 4, -1],
101 turn: 0,
102 attach: null,
103 },
104 ],
105};
106try {
107 const a = await ok("", "/session", {
108 name: "AI chat qualification",
109 color: "#289b74",
110 });
111 const b = await ok("", "/session", {
112 name: "AI chat collaborator",
113 color: "#486fa4",
114 });
115 const id = randomUUID();
116 ids.push(id);
117 const input = { id, prompt: "Disposable chat fixture", newWorld: true };
118 const job: AIGeneration = await ok(a.token, "/ai/generations", input);
119 world = job.target!;
120 assert.ok(world);
121 assert.ok(job.target_slug);
122 assert.equal((await ok(a.token, "/ai/generations", input)).target, world);
123 assert.equal((await request(b.token, `/worlds/${world}/ai`)).status, 403);
124 assert.equal(
125 (
126 await request(b.token, "/ai/generations", {
127 id: randomUUID(),
128 prompt: "Unauthorized target",
129 target: world,
130 })
131 ).status,
132 403,
133 );
134 assert.equal((await request(b.token, `/ai/generations/${id}`)).status, 403);
135 assert.equal(
136 (await request(b.token, `/ai/generations/${id}/live`)).status,
137 403,
138 );
139 assert.equal(
140 (await request(b.token, `/worlds/${world}/live/ai`)).status,
141 403,
142 );
143 await ok(a.token, `/worlds/${job.target_slug}/join`, {});
144 await ok(b.token, `/worlds/${job.target_slug}/join`, {});
145 const viewer = await ok("", "/session", {
146 name: "AI chat viewer",
147 color: "#486fa4",
148 });
149 await ok(viewer.token, `/worlds/${job.target_slug}/join`, {});
150 await pool.query(
151 "UPDATE world_memberships SET role='viewer' WHERE world=$1 AND guest=$2",
152 [world, viewer.guest],
153 );
154 assert.equal(
155 (await ok(viewer.token, `/worlds/${job.target_slug}/join`, {})).canBuildAI,
156 false,
157 );
158 assert.equal((await ok(viewer.token, `/worlds/${world}/ai`)).length, 1);
159 for (const action of ["run", "cancel", "accept"])
160 assert.equal(
161 (await request(viewer.token, `/ai/generations/${id}/${action}`, {}))
162 .status,
163 403,
164 );
165 assert.equal(
166 (
167 await request(viewer.token, "/ai/generations", {
168 id: randomUUID(),
169 prompt: "Viewer cannot build",
170 target: world,
171 })
172 ).status,
173 403,
174 );
175 const peerSub = client.subscribe<AIConversationRow>(
176 await ok(b.token, `/worlds/${world}/live/ai`),
177 );
178 await peerSub.awaitRows(
179 (rows) =>
180 rows.some(
181 (r) => r.id === id && r.author === a.guest && r.author_name === a.name,
182 ),
183 20000,
184 );
185 const deniedId = randomUUID();
186 assert.equal(
187 (
188 await request(b.token, "/ai/generations", {
189 id: deniedId,
190 prompt: "Competing workshop build",
191 target: world,
192 })
193 ).status,
194 409,
195 );
196 assert.equal(
197 (await pool.query("SELECT id FROM ai_generations WHERE id=$1", [deniedId]))
198 .rowCount,
199 0,
200 );
201 assert.equal((await parts()).length, 0);
202 const sub = client.subscribe<AIConversationRow>(
203 await ok(a.token, `/worlds/${world}/live/ai`),
204 );
205 await sub.awaitRows((rows) => rows.some((r) => r.status === "queued"), 20000);
206 await pool.query("UPDATE ai_generations SET status='designing' WHERE id=$1", [
207 id,
208 ]);
209 const drawing = {
210 parts: compileBlueprint(fixture).parts.slice(0, 1),
211 title: "AI chat fixture",
212 };
213 assert.equal(await recordDrawing(id, drawing), true);
214 await sub.awaitRows(
215 (rows) => rows.some((r) => r.preview?.parts.length === 1),
216 20000,
217 );
218 await peerSub.awaitRows(
219 (rows) => rows.some((r) => r.preview?.parts.length === 1),
220 20000,
221 );
222 assert.equal(
223 (await parts()).length,
224 0,
225 "Streaming never mutates the workshop",
226 );
227 await ready(id, fixture);
228 const accepted = await Promise.all(
229 [a, b, a].map((member) =>
230 ok(member.token, `/ai/generations/${id}/accept`, {}),
231 ),
232 );
233 assert.equal(new Set(accepted.map((r) => r.slug)).size, 1);
234 assert.equal(accepted[0].slug, job.target_slug);
235 assert.equal((await parts()).length, 3);
236 assert.equal(
237 await recordDrawing(id, drawing),
238 false,
239 "Accepted drafts reject late stream writes",
240 );
241 await peerSub.awaitRows(
242 (rows) => rows.some((r) => r.id === id && r.status === "accepted"),
243 20000,
244 );
245 const operationOwner = (
246 await pool.query(
247 "SELECT guest FROM build_operations WHERE world=$1 AND id=$2",
248 [world, id],
249 )
250 ).rows[0].guest;
251 const applyingToken = operationOwner === a.guest ? a.token : b.token;
252 const undo = await ok(applyingToken, `/worlds/${world}/edit`, {
253 operationId: randomUUID(),
254 generation: 1,
255 action: "undo",
256 target: id,
257 });
258 assert.equal(undo.accepted, true);
259 assert.equal((await parts()).length, 0);
260 const redo = await ok(applyingToken, `/worlds/${world}/edit`, {
261 operationId: randomUUID(),
262 generation: 1,
263 action: "redo",
264 target: id,
265 });
266 assert.equal(redo.accepted, true);
267 assert.equal((await parts()).length, 3);
268 const original = await parts();
269 const refinementId = randomUUID();
270 ids.push(refinementId);
271 await ok(b.token, "/ai/generations", {
272 id: refinementId,
273 prompt: "Make the roof blue",
274 target: world,
275 });
276 await sub.awaitRows(
277 (rows) => rows.some((r) => r.id === refinementId && r.author === b.guest),
278 20000,
279 );
280 await peerSub.awaitRows(
281 (rows) => rows.some((r) => r.id === refinementId && r.author === b.guest),
282 20000,
283 );
284 const reference = (
285 await pool.query("SELECT reference FROM ai_generations WHERE id=$1", [
286 refinementId,
287 ])
288 ).rows[0].reference;
289 assert.equal(reference.version, 2);
290 assert.equal(reference.pieces.length, 3);
291 const design = {
292 ...reference,
293 pieces: reference.pieces.map((p: any) =>
294 p.part === "slope-2x2" ? { ...p, colour: "cobalt" } : p,
295 ),
296 };
297 await ready(refinementId, design);
298 assert.equal(
299 (await ok(a.token, `/ai/generations/${refinementId}/accept`, {})).slug,
300 job.target_slug,
301 );
302 const changed = await parts();
303 assert.deepEqual(
304 changed.map((p) => p.id),
305 original.map((p) => p.id),
306 );
307 assert.equal(changed.find((p) => p.key === "slope-2x2").color, "#486fa4");
308 const staleId = randomUUID();
309 ids.push(staleId);
310 await ok(a.token, "/ai/generations", {
311 id: staleId,
312 prompt: "A stale draft",
313 target: world,
314 });
315 const staleReference = (
316 await pool.query("SELECT reference FROM ai_generations WHERE id=$1", [
317 staleId,
318 ])
319 ).rows[0].reference;
320 await ready(staleId, staleReference);
321 const moved = changed[0];
322 const edit = await ok(a.token, `/worlds/${world}/edit`, {
323 operationId: randomUUID(),
324 generation: 1,
325 action: "edit",
326 changes: [{ id: moved.id, expected: moved.revision, color: "#edbc46" }],
327 });
328 assert.equal(edit.accepted, true);
329 const conflict = await request(
330 a.token,
331 `/ai/generations/${staleId}/accept`,
332 {},
333 );
334 assert.equal(conflict.status, 409);
335 assert.match(conflict.data.error, /changed while AI/);
336 assert.equal((await parts()).find((p) => p.id === moved.id).color, "#edbc46");
337 await ok(a.token, `/ai/generations/${staleId}/cancel`, {});
338 assert.equal(await recordDrawing(staleId, drawing), false);
339 const history = await ok(a.token, `/worlds/${world}/ai`);
340 assert.equal(history.length, 3);
341 assert.equal(history[1].status, "accepted");
342 const parent = randomUUID(),
343 child = randomUUID();
344 ids.push(parent, child);
345 await ok(a.token, "/ai/generations", {
346 id: parent,
347 prompt: "Unapplied parent draft",
348 target: world,
349 });
350 const parentRef = (
351 await pool.query("SELECT reference FROM ai_generations WHERE id=$1", [
352 parent,
353 ])
354 ).rows[0].reference;
355 await ready(parent, parentRef);
356 await ok(b.token, "/ai/generations", {
357 id: child,
358 prompt: "Refine the unapplied draft",
359 target: world,
360 source: parent,
361 });
362 await ready(child, parentRef);
363 await ok(b.token, `/ai/generations/${child}/cancel`, {});
364 const discarded = await pool.query(
365 "SELECT status FROM ai_generations WHERE id=ANY($1::uuid[])",
366 [[parent, child]],
367 );
368 assert.ok(
369 discarded.rows.every((r) => r.status === "cancelled"),
370 "Discarding a draft does not resurrect earlier unapplied drafts after reload",
371 );
372 const sharedHistory = await ok(b.token, `/worlds/${world}/ai`);
373 assert.equal(
374 sharedHistory.length,
375 5,
376 "All members see the workshop conversation",
377 );
378 assert.equal(
379 sharedHistory.find((r: AIConversationRow) => r.id === refinementId).author,
380 b.guest,
381 );
382 await peerSub.awaitRows(
383 (rows) =>
384 rows.filter(
385 (r) => (r.id === parent || r.id === child) && r.status === "cancelled",
386 ).length === 2,
387 20000,
388 );
389 const raceIds = [randomUUID(), randomUUID()];
390 ids.push(...raceIds);
391 const reservations = await Promise.all(
392 [a, b].map((member, i) =>
393 request(member.token, "/ai/generations", {
394 id: raceIds[i],
395 prompt: "Concurrent workshop reservation",
396 target: world,
397 }),
398 ),
399 );
400 assert.deepEqual(reservations.map((r) => r.status).sort(), [201, 409]);
401 const winner = reservations.find((r) => r.status === 201)!;
402 const otherEditor = winner.data.author === a.guest ? b : a;
403 await ok(otherEditor.token, `/ai/generations/${winner.data.id}/cancel`, {});
404 await pool.query(
405 "UPDATE world_memberships SET active=0 WHERE world=$1 AND guest=$2",
406 [world, b.guest],
407 );
408 await peerSub.awaitRows((rows) => rows.length === 0, 20000);
409 for (const path of [
410 `/worlds/${world}/ai`,
411 `/worlds/${world}/live/ai`,
412 `/ai/generations/${refinementId}`,
413 ])
414 assert.equal((await request(b.token, path)).status, 403);
415 for (const action of ["cancel", "accept"])
416 assert.equal(
417 (await request(b.token, `/ai/generations/${parent}/${action}`, {}))
418 .status,
419 403,
420 );
421 // A different session loses its own subscription on revocation; the author's
422 // session does not control collaborators' access to workshop chat.
423 const viewerSub = client.subscribe<AIConversationRow>(
424 await ok(viewer.token, `/worlds/${world}/live/ai`),
425 );
426 await viewerSub.awaitRows((rows) => rows.length === 6, 20000);
427 await pool.query("UPDATE guest_sessions SET revoked=1 WHERE guest=$1", [
428 a.guest,
429 ]);
430 await viewerSub.awaitRows((rows) => rows.length === 6, 20000);
431 await pool.query("UPDATE guest_sessions SET revoked=1 WHERE guest=$1", [
432 viewer.guest,
433 ]);
434 await viewerSub.awaitRows((rows) => rows.length === 0, 20000);
435 viewerSub.unsubscribe();
436 peerSub.unsubscribe();
437 sub.unsubscribe();
438 console.log(
439 "AI chat lifecycle passed: blank workshop, idempotency, shared authored history, peer prompt discovery and drawings, viewer permissions, withdrawal/revocation, workshop concurrency, atomic same-model apply, undo/redo, identity-preserving refinement, concurrent-edit conflict, and late-stream rejection. No inference calls.",
440 );
441} finally {
442 client.close();
443 if (world)
444 await pool.query("UPDATE worlds SET status='closed' WHERE id=$1", [world]);
445 if (ids.length)
446 await pool.query("DELETE FROM ai_generations WHERE id=ANY($1::uuid[])", [
447 ids,
448 ]);
449 await pool.end();
450}