Open History to see the last commit
1import { useMemo, useState } from 'react';
2import { createOptimisticAction } from '@tanstack/db';
3import type { Message, Run } from '@glow/contracts';
4import type { GlowApi } from './index.ts';
5import { optimisticSyncError, type Feed } from './feeds.ts';
6
7export function createChatScrollFollow() {
8 let following = true, previousOffset = 0;
9 return {
10 get following() { return following; },
11 resume() { following = true; },
12 observe(offset: number, contentHeight: number, viewportHeight: number) {
13 if (viewportHeight <= 0) return;
14 const distance = Math.max(0, contentHeight - viewportHeight - offset);
15 if (distance <= 48) following = true;
16 // Content growth moves the bottom; only upward movement pauses following.
17 else if (offset < previousOffset - 1) following = false;
18 previousOffset = offset;
19 },
20 };
21}
22
23export type BuilderPersist = (text: string, operationId: string, questionId?: string) => Promise<unknown>;
24
25export async function sendOptimisticMessage(api: GlowApi, appId: string, messages: Feed<Message>, text: string, operationId: string, questionId?: string) {
26 const existing = messages.collection.get(operationId);
27 if (existing && !existing.$hasPendingWrites) return;
28 const message: Message = { id: operationId, appId, role: 'user', content: text, runId: null, sequence: Number.MAX_SAFE_INTEGER, createdAt: new Date().toISOString(), ...(questionId ? { answerTo: questionId } : {}) };
29 const mutate = createOptimisticAction({
30 onMutate() { messages.collection.insert({ id: message.id, data: message }); },
31 async mutationFn() {
32 const result = questionId ? await api.answer(appId, questionId, text, operationId) : await api.send(appId, text, operationId);
33 try { await messages.confirm(result.txid); }
34 catch { throw optimisticSyncError(); }
35 },
36 });
37 const release = messages.holdRefresh?.();
38 try { await mutate(undefined).when('settled'); }
39 finally { release?.(); }
40}
41
42export function createBuilderSender(api: GlowApi, appId: string, persist: BuilderPersist = (text, operationId, questionId) => questionId ? api.answer(appId, questionId, text, operationId) : api.send(appId, text, operationId)) {
43 let operation: { text: string; questionId?: string; id: string } | undefined, sending = false;
44 return async (text: string, questionId?: string) => {
45 if (sending) throw new Error('Your reply is being sent.');
46 const trimmed = text.trim();
47 if (!trimmed) throw new Error('Enter a reply.');
48 if (operation?.text !== trimmed || operation.questionId !== questionId) operation = { text: trimmed, questionId, id: crypto.randomUUID() };
49 sending = true;
50 try {
51 const result = await persist(trimmed, operation.id, questionId);
52 operation = undefined;
53 return result;
54 } finally { sending = false; }
55 };
56}
57
58export function useBuilderChat(api: GlowApi, appId: string, runs: Run[], persist: BuilderPersist) {
59 const send = useMemo(() => createBuilderSender(api, appId, persist), [api, appId, persist]);
60 const [sending, setSending] = useState(false);
61 const waiting = runs.find(run => run.status === 'waiting');
62 return { waiting, sending, async send(text: string) {
63 setSending(true);
64 try { return await send(text, waiting?.questionId); }
65 finally { setSending(false); }
66 } };
67}