Open History to see the last commit
1import { memo, useEffect, useRef, useState } from "react";
2import { ArrowUp, Check, LoaderCircle, Sparkles, X } from "lucide-react";
3import type { AIGeneration } from "../shared/types";
4import {
5 activeAIStates as activeStates,
6 conversationRows,
7 conversationState,
8} from "./ai-conversation";
9import { api, watchConversation } from "./store";
10
11const stages: Record<string, string> = {
12 queued: "Getting ready",
13 designing: "Designing the model",
14 checking: "Checking the fit",
15 repairing: "Adjusting the design",
16};
17export default function AIBuildPanel({
18 world,
19 guest,
20 editable,
21 onClose,
22 onPreview,
23}: {
24 world: string;
25 guest: string;
26 editable: boolean;
27 onClose: () => void;
28 onPreview: (draft: AIGeneration | null) => void;
29}) {
30 const [jobs, setJobs] = useState<AIGeneration[]>([]);
31 const { job, preview } = conversationState(jobs);
32 const [prompt, setPrompt] = useState("");
33 const [error, setError] = useState("");
34 const [queryStatus, setQueryStatus] = useState("connecting");
35 const [queryError, setQueryError] = useState("");
36 const [retry, setRetry] = useState(0);
37 const loading = queryStatus === "connecting";
38 const live = queryStatus === "live";
39 const [submitting, setSubmitting] = useState(false);
40 const [applying, setApplying] = useState(false);
41 const [elapsed, setElapsed] = useState(0);
42 const [available, setAvailable] = useState<boolean | null>(null);
43 const mounted = useRef(true);
44 const log = useRef<HTMLDivElement>(null);
45 const composer = useRef<HTMLTextAreaElement>(null);
46 const submission = useRef(false);
47 const busy = !!job && activeStates.includes(job.status);
48 const drawing = busy && job?.preview?.parts.length ? job : preview;
49
50 useEffect(() => {
51 mounted.current = true;
52 setQueryStatus("connecting");
53 setQueryError("");
54 const abort = new AbortController();
55 let alive = true,
56 stop: (() => void) | undefined;
57 void api<{ available: boolean }>("/ai/config")
58 .then((config) => {
59 if (alive) setAvailable(config.available);
60 })
61 .catch((e) => {
62 if (alive) setError(e.message);
63 });
64 void watchConversation(
65 world,
66 ({ data, status, error }) => {
67 if (!alive) return;
68 setQueryStatus(status);
69 setQueryError(error || "");
70 if (status === "live" || status === "error")
71 setJobs((previous) => conversationRows(data, previous));
72 },
73 abort.signal,
74 )
75 .then((off) => {
76 if (alive) stop = off;
77 else off();
78 })
79 .catch((e) => {
80 if (alive) {
81 setQueryStatus("error");
82 setQueryError(e.message);
83 }
84 });
85 return () => {
86 alive = false;
87 abort.abort();
88 mounted.current = false;
89 stop?.();
90 onPreview(null);
91 };
92 }, [world, onPreview, retry]);
93 useEffect(() => {
94 onPreview(drawing);
95 }, [drawing, onPreview]);
96 useEffect(() => {
97 const update = () =>
98 setElapsed(
99 job?.created_at
100 ? Math.max(
101 0,
102 Math.floor((Date.now() - Date.parse(job.created_at)) / 1000),
103 )
104 : 0,
105 );
106 update();
107 if (!busy) return;
108 const timer = setInterval(update, 1000);
109 return () => clearInterval(timer);
110 }, [job?.id, busy]);
111 useEffect(() => {
112 log.current?.scrollTo({
113 top: log.current.scrollHeight,
114 behavior: "smooth",
115 });
116 }, [jobs.length, job?.status, error, preview?.id]);
117
118 async function send() {
119 if (
120 submission.current ||
121 busy ||
122 !live ||
123 applying ||
124 !editable ||
125 !available ||
126 prompt.trim().length < 3
127 )
128 return;
129 submission.current = true;
130 setSubmitting(true);
131 setError("");
132 const id = crypto.randomUUID(),
133 text = prompt.trim();
134 try {
135 await api<AIGeneration>("/ai/generations", {
136 method: "POST",
137 body: JSON.stringify({
138 id,
139 prompt: text,
140 target: world,
141 ...(preview ? { source: preview.id } : {}),
142 }),
143 }).catch(async (e) => {
144 try {
145 return await api<AIGeneration>(`/ai/generations/${id}`);
146 } catch {
147 throw e;
148 }
149 });
150 if (mounted.current) setPrompt("");
151 } catch (e) {
152 if (mounted.current) setError((e as Error).message);
153 } finally {
154 submission.current = false;
155 if (mounted.current) setSubmitting(false);
156 }
157 }
158 async function cancel() {
159 if (!job || !editable || !live) return;
160 try {
161 await api(`/ai/generations/${job.id}/cancel`, { method: "POST" });
162 } catch (e) {
163 if (mounted.current) setError((e as Error).message);
164 }
165 }
166 async function apply() {
167 if (!preview || busy || applying || !editable || !live) return;
168 setApplying(true);
169 setError("");
170 try {
171 const result = await api<{ slug: string }>(
172 `/ai/generations/${preview.id}/accept`,
173 { method: "POST" },
174 );
175 if (!mounted.current) return;
176 if (!preview.target) {
177 location.assign(`/w/${result.slug}?ai=1&frame=1`);
178 return;
179 }
180 composer.current?.focus();
181 } catch (e) {
182 if (mounted.current) setError((e as Error).message);
183 } finally {
184 if (mounted.current) setApplying(false);
185 }
186 }
187 async function discard() {
188 if (!preview || busy || applying || !editable || !live) return;
189 try {
190 await api(`/ai/generations/${preview.id}/cancel`, { method: "POST" });
191 if (!mounted.current) return;
192 setError("");
193 composer.current?.focus();
194 } catch (e) {
195 if (mounted.current) setError((e as Error).message);
196 }
197 }
198 return (
199 <aside
200 className="ai-chat"
201 aria-label="AI building chat"
202 onKeyDown={(e) => e.stopPropagation()}
203 >
204 <div className="ai-chat-heading">
205 <span>
206 <Sparkles size={16} />
207 Build with AI
208 </span>
209 <button
210 className="icon-button"
211 aria-label="Close AI chat"
212 onClick={onClose}
213 >
214 <X size={17} />
215 </button>
216 </div>
217 <div
218 className="ai-chat-log"
219 ref={log}
220 role="log"
221 aria-label="Build conversation"
222 >
223 {loading ? (
224 <p className="ai-chat-empty">Opening the conversation…</p>
225 ) : (
226 !jobs.length && (
227 <div className="ai-chat-empty">
228 <h2>Keep shaping it.</h2>
229 <p>
230 Ask for a new detail, a different colour, or something entirely
231 new.
232 </p>
233 </div>
234 )
235 )}
236 {jobs.map((row) => (
237 <AIExchange
238 key={row.id}
239 row={row}
240 guest={guest}
241 current={row.id === job?.id}
242 elapsed={row.id === job?.id ? elapsed : 0}
243 />
244 ))}
245 </div>
246 {preview && !busy && (
247 <div className="ai-chat-review">
248 <span>Previewing the workshop draft</span>
249 <div>
250 <button
251 className="primary-button"
252 disabled={applying || submitting || !editable || !live}
253 onClick={() => void apply()}
254 >
255 {applying ? "Applying…" : "Apply to model"}
256 <Check size={14} />
257 </button>
258 <button
259 className="ai-secondary"
260 disabled={applying || submitting || !editable || !live}
261 onClick={() => void discard()}
262 >
263 Keep current
264 </button>
265 </div>
266 </div>
267 )}
268 {!live && !loading && (
269 <div className="ai-chat-error" role="status">
270 <p>
271 {queryError ||
272 "Chat is reconnecting. Changes will be available when it is live again."}
273 </p>
274 {queryStatus === "error" && (
275 <button
276 className="ai-secondary"
277 onClick={() => setRetry((n) => n + 1)}
278 >
279 Reconnect chat
280 </button>
281 )}
282 </div>
283 )}
284 {error && (
285 <p className="ai-error ai-chat-error" role="alert">
286 {error}
287 </p>
288 )}
289 {available === false && (
290 <p className="ai-error ai-chat-error">
291 AI building is not available right now.
292 </p>
293 )}
294 <form
295 className="ai-composer"
296 onSubmit={(e) => {
297 e.preventDefault();
298 void send();
299 }}
300 >
301 <label className="sr-only" htmlFor="ai-chat-prompt">
302 Ask AI to change the model
303 </label>
304 <textarea
305 id="ai-chat-prompt"
306 ref={composer}
307 rows={3}
308 maxLength={1200}
309 placeholder={
310 preview
311 ? "Make this draft a little more…"
312 : "What would you like to change?"
313 }
314 value={prompt}
315 disabled={!live || applying || !editable}
316 onChange={(e) => setPrompt(e.target.value)}
317 onKeyDown={(e) => {
318 if (
319 e.key === "Enter" &&
320 !e.shiftKey &&
321 !e.nativeEvent.isComposing
322 ) {
323 e.preventDefault();
324 void send();
325 }
326 }}
327 />
328 <div className="ai-composer-actions">
329 <small>
330 {!editable
331 ? "You can follow this workshop’s AI builds."
332 : busy
333 ? "You can write your next idea while I work."
334 : "Enter to send · Shift Enter for a new line"}
335 </small>
336 {busy ? (
337 <button
338 type="button"
339 className="ai-secondary"
340 disabled={!editable || !live}
341 onClick={() => void cancel()}
342 >
343 Stop
344 </button>
345 ) : (
346 <button
347 className="ai-send"
348 aria-label="Send build request"
349 disabled={
350 !editable ||
351 !available ||
352 !live ||
353 submitting ||
354 applying ||
355 prompt.trim().length < 3
356 }
357 >
358 {submitting ? (
359 <LoaderCircle size={16} className="spin" />
360 ) : (
361 <ArrowUp size={18} />
362 )}
363 </button>
364 )}
365 </div>
366 </form>
367 </aside>
368 );
369}
370
371const AIExchange = memo(function AIExchange({
372 row,
373 guest,
374 current,
375 elapsed,
376}: {
377 row: AIGeneration;
378 guest: string;
379 current: boolean;
380 elapsed: number;
381}) {
382 return (
383 <div className="ai-exchange">
384 <div className="ai-message-label">
385 <span
386 className="ai-author-dot"
387 style={{ background: row.author_color || "var(--green)" }}
388 />
389 {row.author_name || "Builder"}
390 {row.author === guest ? " · you" : ""}
391 </div>
392 <p className="ai-user-message">{row.prompt}</p>
393 <div className="ai-message-label ai-assistant-label">
394 <Sparkles size={12} />
395 neonbricks
396 </div>
397 {activeStates.includes(row.status) ? (
398 <div className="ai-live-message">
399 <span>
400 <LoaderCircle size={14} className="spin" />
401 {row.activity || stages[row.status]}
402 </span>
403 {current && (
404 <small>
405 {elapsed}s{row.attempt > 1 ? ` · design pass ${row.attempt}` : ""}
406 </small>
407 )}
408 <p>
409 {row.preview?.parts.length
410 ? "A draft is taking shape on the canvas."
411 : "Your current model stays safe while I work."}
412 </p>
413 </div>
414 ) : row.status === "failed" ? (
415 <p className="ai-error">
416 {row.error || "This build was interrupted. Please try again."}
417 </p>
418 ) : row.status === "cancelled" ? (
419 <p className="ai-chat-note">
420 Draft set aside. The workshop is unchanged.
421 </p>
422 ) : (
423 <>
424 <p className="ai-assistant-message">
425 {row.blueprint?.summary &&
426 row.blueprint.summary !== "The current workshop model."
427 ? row.blueprint.summary
428 : row.status === "accepted"
429 ? "Your changes are applied."
430 : "Your updated draft is ready."}
431 </p>
432 <span className="ai-chat-result">
433 {row.status === "accepted" ? (
434 <>
435 <Check size={12} />
436 Applied to the model
437 </>
438 ) : (
439 `${row.piece_count ?? row.parts.length} pieces · draft ready`
440 )}
441 </span>
442 </>
443 )}
444 </div>
445 );
446});