The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Chat: a free text chat for accounts, with characters, ideas, writing tools and shares
Adarshf70a279098a8
diff --git a/src/app/(studio)/chat/[id]/page.tsx b/src/app/(studio)/chat/[id]/page.tsxnew file mode 100644index 00000000..fa247df5--- /dev/null+++ b/src/app/(studio)/chat/[id]/page.tsx@@ -0,0 +1,18 @@+import type { Metadata } from "next";+import { Suspense } from "react";+import { ThreadView } from "@/components/chat/thread-view";++export const metadata: Metadata = { title: "Chat" };++async function Thread({ params }: { params: PageProps<"/chat/[id]">["params"] }) {+ const { id } = await params;+ return <ThreadView id={id} />;+}++export default function Page({ params }: PageProps<"/chat/[id]">) {+ return (+ <Suspense>+ <Thread params={params} />+ </Suspense>+ );+}diff --git a/src/app/(studio)/chat/page.tsx b/src/app/(studio)/chat/page.tsxnew file mode 100644index 00000000..1e07030b--- /dev/null+++ b/src/app/(studio)/chat/page.tsx@@ -0,0 +1,16 @@+import type { Metadata } from "next";+import { Suspense } from "react";+import { ChatHome } from "@/components/chat/chat-home";++export const metadata: Metadata = {+ title: "Chat",+ description: "Free AI chat on Fuobe: ask anything, brainstorm ideas you can make in one tap, write captions and scripts, or step into a story with a character.",+};++export default function Page() {+ return (+ <Suspense>+ <ChatHome />+ </Suspense>+ );+}diff --git a/src/app/api/chat/characters/[id]/route.ts b/src/app/api/chat/characters/[id]/route.tsnew file mode 100644index 00000000..c83fecd5--- /dev/null+++ b/src/app/api/chat/characters/[id]/route.ts@@ -0,0 +1,34 @@+import { body, chatViewer, refused, signUp, tooOften } from "@/server/chat/http";+import { ownPicture } from "@/server/chat/files";+import { deleteCharacter, getPrefs, updateCharacter } from "@/server/chat/store";+import { CharacterBody } from "@/server/chat/schemas";++/** Change one of the person's characters. */+export async function PATCH(request: Request, ctx: RouteContext<"/api/chat/characters/[id]">) {+ const v = chatViewer(request);+ if (!v) return signUp();+ const limited = tooOften(v.who, "characters", 30);+ if (limited) return limited;+ const { id } = await ctx.params;+ const p = CharacterBody.safeParse(await body(request));+ if (!p.success) return Response.json({ error: "That character couldn't be read." }, { status: 400 });+ if (p.data.mature && !getPrefs(v.who).mature) return Response.json({ error: "Turn on Mango Chilli mode to make a mature character.", code: "mature-off" }, { status: 403 });+ let portrait: string | null | undefined = undefined;+ if (p.data.portrait !== undefined) {+ portrait = p.data.portrait ? ownPicture(v.who, p.data.portrait) : null;+ if (p.data.portrait && !portrait) return Response.json({ error: "That portrait couldn't be read. Pick it again." }, { status: 400 });+ }+ try {+ return Response.json(updateCharacter(v.who, id, { ...p.data, ...(portrait !== undefined && { portrait }) }));+ } catch (e) {+ return refused(e);+ }+}++/** Delete one of the person's characters. Its chats stay. */+export async function DELETE(request: Request, ctx: RouteContext<"/api/chat/characters/[id]">) {+ const v = chatViewer(request);+ if (!v) return signUp();+ const { id } = await ctx.params;+ return deleteCharacter(v.who, id) ? Response.json({ ok: true }) : Response.json({ error: "That character isn't one of yours." }, { status: 404 });+}diff --git a/src/app/api/chat/characters/route.ts b/src/app/api/chat/characters/route.tsnew file mode 100644index 00000000..01e6f061--- /dev/null+++ b/src/app/api/chat/characters/route.ts@@ -0,0 +1,55 @@+import { connection } from "next/server";+import { z } from "zod";+import { copyPicture, ownPicture } from "@/server/chat/files";+import { body, chatViewer, refused, signUp, tooOften } from "@/server/chat/http";+import { CharacterBody } from "@/server/chat/schemas";+import { createCharacter, findChatShare, getCharacter, getPrefs, listCharacters } from "@/server/chat/store";++/** The characters this person can chat with: their own first, then the built-in ones. Mature ones only in Mango Chilli mode. */+export async function GET(request: Request) {+ await connection();+ const v = chatViewer(request);+ if (!v) return signUp();+ return Response.json({ items: listCharacters(v.who, getPrefs(v.who).mature) });+}++const Post = CharacterBody.extend({+ /** Make a copy of the character in a shared chat ("Chat with them"). */+ fromShare: z.string().max(64).optional(),+});++/** Make a character (or copy one from a shared chat). */+export async function POST(request: Request) {+ const v = chatViewer(request);+ if (!v) return signUp();+ const limited = tooOften(v.who, "characters", 20);+ if (limited) return limited;+ const p = Post.safeParse(await body(request));+ if (!p.success) return Response.json({ error: "That character couldn't be read." }, { status: 400 });+ const mature = getPrefs(v.who).mature;+ try {+ if (p.data.fromShare) {+ const s = findChatShare(p.data.fromShare);+ const c = s?.snapshot.character;+ if (!s || !c) return Response.json({ error: "That shared chat has no character to copy." }, { status: 404 });+ if (s.snapshot.mature && !mature) return Response.json({ error: "Turn on Mango Chilli mode to chat with this character.", code: "mature-off" }, { status: 403 });+ // A built-in character needs no copy: chat with it as it is.+ if (c.builtIn) return Response.json(getCharacter(v.who, c.id), { status: 200 });+ // The person who shared it keeps their own wording private: the copy takes the name, look and the shared lines'+ // voice, and the new owner can change it.+ const source = getCharacter(s.owner, c.id);+ if (!source) return Response.json({ error: "That character was deleted by the person who shared it." }, { status: 404 });+ const portrait = s.portrait ? await copyPicture(v.who, s.portrait) : null;+ return Response.json(+ createCharacter(v.who, { name: source.name, tagline: source.tagline, persona: source.persona, scenario: source.scenario, greeting: source.greeting, mature: source.mature, accent: source.accent, portrait }),+ { status: 201 },+ );+ }+ if (p.data.mature && !mature) return Response.json({ error: "Turn on Mango Chilli mode to make a mature character.", code: "mature-off" }, { status: 403 });+ const portrait = p.data.portrait ? ownPicture(v.who, p.data.portrait) : null;+ if (p.data.portrait && !portrait) return Response.json({ error: "That portrait couldn't be read. Pick it again." }, { status: 400 });+ return Response.json(createCharacter(v.who, { ...p.data, portrait }), { status: 201 });+ } catch (e) {+ return refused(e);+ }+}diff --git a/src/app/api/chat/key/route.ts b/src/app/api/chat/key/route.tsnew file mode 100644index 00000000..4bdf8692--- /dev/null+++ b/src/app/api/chat/key/route.ts@@ -0,0 +1,42 @@+import { z } from "zod";+import { checkOpenRouterKey } from "@/server/chat/backend";+import { body, chatViewer, signUp, tooOften } from "@/server/chat/http";+import { removeChatKey, saveChatKey } from "@/server/chat/store";++const Put = z.object({+ key: z+ .string()+ .trim()+ .regex(/^sk-or-[\w-]{20,200}$/),+ model: z+ .string()+ .trim()+ .regex(/^[\w.:/-]{3,120}$/)+ .nullish(),+});++/**+ * Save the person's own OpenRouter key for chat, checked with OpenRouter first (a free call). It is sealed on the+ * server and never sent back; only its last four characters show.+ */+export async function PUT(request: Request) {+ const v = chatViewer(request);+ if (!v) return signUp();+ // A check reaches OpenRouter: a few a minute.+ const limited = tooOften(v.who, "key", 6);+ if (limited) return limited;+ const p = Put.safeParse(await body(request));+ if (!p.success) return Response.json({ error: "That doesn't look like an OpenRouter key. It starts with sk-or-." }, { status: 400 });+ const check = await checkOpenRouterKey(p.data.key);+ if (check === "refused") return Response.json({ error: "OpenRouter didn't accept that key. Copy it again from openrouter.ai/settings/keys." }, { status: 422 });+ if (check === "unreachable") return Response.json({ error: "Couldn't reach OpenRouter to check the key. Try again in a moment." }, { status: 503 });+ const prefs = saveChatKey(v.who, p.data.key, p.data.model ?? null);+ return Response.json({ key: prefs.key, engine: prefs.engine });+}++export async function DELETE(request: Request) {+ const v = chatViewer(request);+ if (!v) return signUp();+ const prefs = removeChatKey(v.who);+ return Response.json({ key: prefs.key, engine: prefs.engine });+}diff --git a/src/app/api/chat/me/route.ts b/src/app/api/chat/me/route.tsnew file mode 100644index 00000000..6d99eaac--- /dev/null+++ b/src/app/api/chat/me/route.ts@@ -0,0 +1,50 @@+import { connection } from "next/server";+import { z } from "zod";+import type { ChatMe } from "@/lib/chat/types";+import { siteStatus } from "@/server/chat/backend";+import { body, chatViewer, refused, signUp, tooOften } from "@/server/chat/http";+import { getPrefs, setEngine, setKeyModel, setMature } from "@/server/chat/store";++function me(who: string, owner: boolean): ChatMe {+ const p = getPrefs(who);+ const s = siteStatus(who);+ return { site: s.on, siteKnown: s.known, key: p.key, engine: p.engine, mature: p.mature, owner };+}++/** The person's chat settings and what can answer them now. */+export async function GET(request: Request) {+ await connection();+ const v = chatViewer(request);+ if (!v) return signUp();+ return Response.json(me(v.who, v.owner));+}++const Patch = z.object({+ /** Mango Chilli mode: turning it on needs `adult: true` (the person said they're 18 or older). */+ mature: z.boolean().optional(),+ adult: z.boolean().optional(),+ engine: z.enum(["site", "key"]).optional(),+ model: z+ .string()+ .trim()+ .regex(/^[\w.:/-]{3,120}$/)+ .optional(),+});++export async function PATCH(request: Request) {+ const v = chatViewer(request);+ if (!v) return signUp();+ const limited = tooOften(v.who);+ if (limited) return limited;+ const p = Patch.safeParse(await body(request));+ if (!p.success) return Response.json({ error: "Those settings couldn't be read." }, { status: 400 });+ try {+ if (p.data.mature === true && p.data.adult !== true) return Response.json({ error: "Confirm you're 18 or older to turn on Mango Chilli mode.", code: "adult" }, { status: 400 });+ if (p.data.mature !== undefined) setMature(v.who, p.data.mature);+ if (p.data.model) setKeyModel(v.who, p.data.model);+ if (p.data.engine) setEngine(v.who, p.data.engine);+ return Response.json(me(v.who, v.owner));+ } catch (e) {+ return refused(e);+ }+}diff --git a/src/app/api/chat/threads/[id]/reply/route.ts b/src/app/api/chat/threads/[id]/reply/route.tsnew file mode 100644index 00000000..1d64e461--- /dev/null+++ b/src/app/api/chat/threads/[id]/reply/route.ts@@ -0,0 +1,177 @@+import { z } from "zod";+import { CHAT_LIMITS } from "@/lib/chat/catalog";+import { systemPrompt, type ChatTurn } from "@/lib/chat/prompt";+import type { ChatEvent } from "@/lib/chat/types";+import { chatReply, CHAT_WORDS, summarize } from "@/server/chat/backend";+import { ownPicture, readPicture } from "@/server/chat/files";+import { body, chatViewer, gone, refused, signUp } from "@/server/chat/http";+import { addMessage, chatKey, dropLastReply, getPrefs, getThread, rewindTo, setSummary, threadMemory, threadTurns } from "@/server/chat/store";+import { enter, hit } from "@/server/rate";++const Post = z.object({+ /** A new message. Without one, the chat's last message (the person's) is answered: a new chat's first, or Try again. */+ text: z.string().max(CHAT_LIMITS.messageChars).nullish(),+ image: z.string().max(400).nullish(),+ /** Try again: the last reply goes and is written again. */+ retry: z.boolean().optional(),+ /** Change one of the person's messages: it and everything after it go, and `text` takes its place. */+ edit: z.string().max(60).nullish(),+});++const TEMPERATURE = { chat: 0.7, ideas: 0.95, write: 0.7, character: 1.0, play: 1.0 } as const;++/** A summary is brought up to date once this many turns have fallen out of what the model sees. */+const SUMMARY_EVERY = 6;++/**+ * Answer in a chat. The answer streams as one JSON object per line (ChatEvent): the person's message as saved, the+ * reply as it is written, then the saved reply, or what went wrong. The person's message stays when a reply fails, so+ * Try again answers it.+ */+export async function POST(request: Request, ctx: RouteContext<"/api/chat/threads/[id]/reply">) {+ const v = chatViewer(request);+ if (!v) return signUp();+ const { id } = await ctx.params;+ const p = Post.safeParse(await body(request));+ if (!p.success) return Response.json({ error: `Messages can be up to ${CHAT_LIMITS.messageChars.toLocaleString("en")} characters.` }, { status: 400 });+ const thread = getThread(v.who, id);+ if (!thread) return gone();+ const prefs = getPrefs(v.who);+ if (thread.mature && !prefs.mature) return Response.json({ error: "This chat is in Mango Chilli mode. Turn it on to carry on.", code: "mature-off" }, { status: 403 });++ // Replies a minute per person, on any engine (the free helper counts its own use too).+ if (v.who !== "owner") {+ const r = hit(`chat-reply:${v.who}`, 20, 60_000);+ if (!r.ok) return Response.json({ error: CHAT_WORDS.limit, code: "limit" }, { status: 429, headers: { "Retry-After": String(r.retryAfterS) } });+ }+ // One reply at a time per person.+ const leave = v.who === "owner" ? () => {} : enter(`chat-replying:${v.who}`, 1);+ if (!leave) return Response.json({ error: "A reply is still being written. Wait for it, then send again.", code: "busy" }, { status: 409 });++ let userMessage = null;+ try {+ const text = p.data.text?.trim() ?? "";+ const image = p.data.image ? ownPicture(v.who, p.data.image) : null;+ if (p.data.image && !image) throw Object.assign(new Error("That picture couldn't be read. Add it again."), { status: 400 });+ if (p.data.edit) {+ if (!text) throw Object.assign(new Error("Write the new message first."), { status: 400 });+ if (!rewindTo(v.who, id, p.data.edit)) throw Object.assign(new Error("That message can't be changed."), { status: 409 });+ } else if (p.data.retry) dropLastReply(v.who, id);+ if (text || image) userMessage = addMessage(v.who, id, "user", text, image);+ } catch (e) {+ leave();+ const status = (e as { status?: number }).status;+ return status ? Response.json({ error: (e as Error).message }, { status }) : refused(e);+ }++ const turns = threadTurns(v.who, id);+ const last = turns.at(-1);+ if (!last || last.role !== "user") {+ leave();+ return Response.json({ error: "There's nothing to answer yet.", code: "nothing" }, { status: 409 });+ }+ const memory = threadMemory(v.who, id);+ const character = thread.characterCard;+ const speaker = character?.name ?? "You";+ const system = systemPrompt({ kind: thread.kind, character, tool: thread.tool, play: thread.play, mature: prefs.mature, summary: memory?.summary });+ // What the model reads: the summary covers turns up to summary_upto; a picture-only turn says so in words.+ const asTurn = (m: (typeof turns)[number]): ChatTurn => ({ role: m.role, content: m.content || (m.image ? "(sent a picture)" : "") });+ const visible = turns.filter((m) => m.seq > (memory?.upto ?? 0)).map(asTurn);+ const picture = last.image ? await readPicture(v.who, last.image) : null;+ const key = prefs.engine === "key" ? chatKey(v.who) : null;++ const enc = new TextEncoder();+ const abort = new AbortController();+ request.signal.addEventListener("abort", () => abort.abort(), { once: true });++ let released = false;+ const release = () => {+ if (!released) leave();+ released = true;+ };++ const stream = new ReadableStream<Uint8Array>({+ async start(controller) {+ let open = true;+ const close = () => {+ open = false;+ try {+ controller.close();+ } catch {+ // Already closed: the person left.+ }+ };+ const send = (e: ChatEvent) => {+ if (!open) return;+ try {+ controller.enqueue(enc.encode(`${JSON.stringify(e)}\n`));+ } catch {+ open = false;+ }+ };+ // Text as it's written, at most every 60 ms (the last always goes).+ let pending: string | null = null;+ let timer: ReturnType<typeof setTimeout> | null = null;+ const flush = () => {+ timer = null;+ if (pending !== null) send({ type: "text", text: pending });+ pending = null;+ };+ try {+ if (userMessage) send({ type: "user", message: userMessage });+ const answer = await chatReply(+ prefs.engine,+ {+ who: v.who,+ system,+ turns: visible,+ speaker,+ image: picture,+ temperature: TEMPERATURE[thread.kind],+ signal: abort.signal,+ onText: (t) => {+ pending = t;+ timer ??= setTimeout(flush, 60);+ },+ },+ key,+ );+ if (timer) clearTimeout(timer);+ flush();+ if ("error" in answer) {+ send({ type: "error", code: answer.error, message: answer.message, ...(answer.retryAfterS && { retryAfterS: answer.retryAfterS }) });+ return;+ }+ const saved = addMessage(v.who, id, "assistant", answer.text);+ send({ type: "done", message: saved, title: getThread(v.who, id)?.title ?? thread.title });+ release();+ close();+ // Keep a long chat coherent: once enough turns have fallen out of view, fold them into the summary (after+ // the reply is out, so the person can carry on meanwhile).+ if (answer.dropped >= SUMMARY_EVERY) {+ const fold = threadTurns(v.who, id)+ .filter((m) => m.seq > (memory?.upto ?? 0))+ .slice(0, answer.dropped);+ const upto = fold.at(-1)?.seq;+ if (upto) {+ const s = await summarize(v.who, memory?.summary ?? null, fold.map(asTurn), speaker, key).catch(() => null);+ if (s) setSummary(v.who, id, s, upto);+ }+ }+ } catch {+ send({ type: "error", code: "failed", message: CHAT_WORDS.failed });+ } finally {+ release();+ close();+ }+ },+ cancel() {+ // The person left: the reply stops; what was sent before stays.+ abort.abort();+ },+ });++ return new Response(stream, {+ headers: { "Content-Type": "application/x-ndjson; charset=utf-8", "Cache-Control": "no-store", "X-Accel-Buffering": "no" },+ });+}diff --git a/src/app/api/chat/threads/[id]/route.ts b/src/app/api/chat/threads/[id]/route.tsnew file mode 100644index 00000000..38dabfd1--- /dev/null+++ b/src/app/api/chat/threads/[id]/route.ts@@ -0,0 +1,40 @@+import { connection } from "next/server";+import { z } from "zod";+import { body, chatViewer, gone, refused, signUp, tooOften } from "@/server/chat/http";+import { deleteThread, getPrefs, getThread, renameThread } from "@/server/chat/store";++/** One of the person's chats with its messages (another's reads as gone). */+export async function GET(request: Request, ctx: RouteContext<"/api/chat/threads/[id]">) {+ await connection();+ const v = chatViewer(request);+ if (!v) return signUp();+ const { id } = await ctx.params;+ const t = getThread(v.who, id);+ if (!t) return gone();+ if (t.mature && !getPrefs(v.who).mature) return Response.json({ error: "This chat is in Mango Chilli mode. Turn it on to open it.", code: "mature-off" }, { status: 403 });+ return Response.json(t);+}++const Patch = z.object({ title: z.string().max(200) });++export async function PATCH(request: Request, ctx: RouteContext<"/api/chat/threads/[id]">) {+ const v = chatViewer(request);+ if (!v) return signUp();+ const limited = tooOften(v.who);+ if (limited) return limited;+ const { id } = await ctx.params;+ const p = Patch.safeParse(await body(request));+ if (!p.success) return Response.json({ error: "Give the chat a name." }, { status: 400 });+ try {+ return Response.json(renameThread(v.who, id, p.data.title));+ } catch (e) {+ return refused(e);+ }+}++export async function DELETE(request: Request, ctx: RouteContext<"/api/chat/threads/[id]">) {+ const v = chatViewer(request);+ if (!v) return signUp();+ const { id } = await ctx.params;+ return deleteThread(v.who, id) ? Response.json({ ok: true }) : gone();+}diff --git a/src/app/api/chat/threads/[id]/share/route.ts b/src/app/api/chat/threads/[id]/share/route.tsnew file mode 100644index 00000000..f2770d97--- /dev/null+++ b/src/app/api/chat/threads/[id]/share/route.ts@@ -0,0 +1,34 @@+import { z } from "zod";+import { body, chatViewer, refused, signUp, tooOften } from "@/server/chat/http";+import { shareThread, unshareThread } from "@/server/chat/store";++const Post = z.object({ messageIds: z.array(z.string().max(60)).max(40).nullish() });++/**+ * Share a chat at a public link: a copy of its last messages (or the ones picked) as they are now. Nothing is public+ * until the person does this, and sharing again makes a new link (the old one stops working).+ */+export async function POST(request: Request, ctx: RouteContext<"/api/chat/threads/[id]/share">) {+ const v = chatViewer(request);+ if (!v) return signUp();+ const limited = tooOften(v.who, "share", 10);+ if (limited) return limited;+ const { id } = await ctx.params;+ const p = Post.safeParse(await body(request));+ if (!p.success) return Response.json({ error: "Pick the messages to share." }, { status: 400 });+ try {+ const s = shareThread(v.who, id, { messageIds: p.data.messageIds });+ return Response.json({ token: s.token, path: `/c/${s.token}`, snapshot: s.snapshot }, { status: 201 });+ } catch (e) {+ return refused(e);+ }+}++/** Stop sharing: the link stops working at once. */+export async function DELETE(request: Request, ctx: RouteContext<"/api/chat/threads/[id]/share">) {+ const v = chatViewer(request);+ if (!v) return signUp();+ const { id } = await ctx.params;+ unshareThread(v.who, id);+ return Response.json({ ok: true });+}diff --git a/src/app/api/chat/threads/route.ts b/src/app/api/chat/threads/route.tsnew file mode 100644index 00000000..61bec978--- /dev/null+++ b/src/app/api/chat/threads/route.ts@@ -0,0 +1,45 @@+import { connection } from "next/server";+import { z } from "zod";+import { CHAT_LIMITS, isChatKind } from "@/lib/chat/catalog";+import { ownPicture } from "@/server/chat/files";+import { body, chatViewer, refused, signUp, tooOften } from "@/server/chat/http";+import { addMessage, createThread, getPrefs, getThread, listThreads } from "@/server/chat/store";++/** The person's chats, newest first (`?q=` finds by title). */+export async function GET(request: Request) {+ await connection();+ const v = chatViewer(request);+ if (!v) return signUp();+ const q = new URL(request.url).searchParams.get("q") ?? undefined;+ return Response.json({ items: listThreads(v.who, { mature: getPrefs(v.who).mature, q }) });+}++const Post = z.object({+ kind: z.string().refine(isChatKind),+ characterId: z.string().max(60).nullish(),+ tool: z.string().max(40).nullish(),+ play: z.string().max(40).nullish(),+ /** The first message: the chat is made with it, and the thread page asks for the reply. */+ text: z.string().max(CHAT_LIMITS.messageChars).nullish(),+ image: z.string().max(400).nullish(),+});++/** Start a chat. A character's chat opens with their greeting. */+export async function POST(request: Request) {+ const v = chatViewer(request);+ if (!v) return signUp();+ const limited = tooOften(v.who, "new", 20);+ if (limited) return limited;+ const p = Post.safeParse(await body(request));+ if (!p.success) return Response.json({ error: "That chat couldn't be started." }, { status: 400 });+ const image = p.data.image ? ownPicture(v.who, p.data.image) : null;+ if (p.data.image && !image) return Response.json({ error: "That picture couldn't be read. Add it again." }, { status: 400 });+ try {+ const t = createThread(v.who, { kind: p.data.kind as never, characterId: p.data.characterId, tool: p.data.tool, play: p.data.play, mature: getPrefs(v.who).mature });+ const text = p.data.text?.trim();+ if (text || image) addMessage(v.who, t.id, "user", text ?? "", image);+ return Response.json(getThread(v.who, t.id), { status: 201 });+ } catch (e) {+ return refused(e);+ }+}diff --git a/src/app/c/[token]/opengraph-image.tsx b/src/app/c/[token]/opengraph-image.tsxnew file mode 100644index 00000000..51854761--- /dev/null+++ b/src/app/c/[token]/opengraph-image.tsx@@ -0,0 +1,82 @@+import { ImageResponse } from "next/og";+import { connection } from "next/server";+import sharp from "sharp";+import { readSharedPicture } from "@/server/chat/files";+import { findChatShare } from "@/server/chat/store";++export const alt = "A chat shared from Fuobe";+export const size = { width: 1200, height: 630 };+export const contentType = "image/png";++/** The plain words of a message for a preview (no markdown marks, one paragraph). */+const plain = (s: string, n: number) => {+ const t = s+ .replace(/[*#_`>]/g, "")+ .replace(/\s+/g, " ")+ .trim();+ return t.length > n ? `${t.slice(0, n - 1).trimEnd()}…` : t;+};++async function portraitUri(ref: string | null): Promise<string | null> {+ if (!ref) return null;+ const pic = await readSharedPicture(ref);+ if (!pic) return null;+ const jpeg = await sharp(pic.data).rotate().resize(520, 630, { fit: "cover" }).jpeg({ quality: 82 }).toBuffer().catch(() => null);+ return jpeg ? `data:image/jpeg;base64,${jpeg.toString("base64")}` : null;+}++/**+ * The link preview of a shared chat: the character's portrait (or their colours) and the opening of the chat. A+ * Mango Chilli chat shows only its title and an 18+ mark, never its words.+ */+export default async function Image({ params }: { params: Promise<{ token: string }> }) {+ await connection();+ const { token } = await params;+ const s = findChatShare(token);+ const snap = s?.snapshot;+ const [a, b] = snap?.character?.accent ?? ["#1d1640", "#6a5ee7"];+ const portrait = snap && !snap.mature ? await portraitUri(s.portrait) : null;+ const name = snap?.character?.name ?? snap?.label ?? "Fuobe Chat";+ const lines = snap && !snap.mature ? snap.messages.filter((m) => m.content.trim()).slice(0, 3) : [];+ return new ImageResponse(+ (+ <div style={{ width: "100%", height: "100%", display: "flex", background: `linear-gradient(135deg, ${a} 0%, ${b} 100%)`, color: "white" }}>+ {portrait ? (+ // eslint-disable-next-line @next/next/no-img-element+ <img src={portrait} width={520} height={630} style={{ objectFit: "cover" }} alt="" />+ ) : (+ <div style={{ width: 420, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 220, fontWeight: 700, opacity: 0.9 }}>{name.slice(0, 1).toUpperCase()}</div>+ )}+ <div style={{ flex: 1, display: "flex", flexDirection: "column", justifyContent: "space-between", padding: "56px 60px", background: "rgba(8,6,16,0.55)" }}>+ <div style={{ display: "flex", flexDirection: "column" }}>+ <div style={{ fontSize: 26, opacity: 0.75, display: "flex" }}>{snap?.mature ? "Mango Chilli · 18+" : "A chat on Fuobe"}</div>+ <div style={{ fontSize: 64, fontWeight: 700, lineHeight: 1.05, marginTop: 10, display: "flex" }}>{plain(name, 40)}</div>+ {snap?.character?.tagline && !snap.mature ? <div style={{ fontSize: 26, opacity: 0.8, marginTop: 10, display: "flex" }}>{plain(snap.character.tagline, 80)}</div> : null}+ </div>+ <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>+ {lines.map((m, i) => (+ <div+ key={i}+ style={{+ display: "flex",+ alignSelf: m.role === "user" ? "flex-end" : "flex-start",+ maxWidth: 560,+ fontSize: 24,+ lineHeight: 1.35,+ padding: "12px 18px",+ borderRadius: 18,+ background: m.role === "user" ? "rgba(255,255,255,0.92)" : "rgba(255,255,255,0.14)",+ color: m.role === "user" ? "#17121f" : "white",+ }}+ >+ {plain(m.content, 120)}+ </div>+ ))}+ </div>+ <div style={{ fontSize: 24, opacity: 0.8, display: "flex" }}>fuobe.com</div>+ </div>+ </div>+ ),+ size,+ );+}diff --git a/src/app/c/[token]/page.tsx b/src/app/c/[token]/page.tsxnew file mode 100644index 00000000..8540d9ac--- /dev/null+++ b/src/app/c/[token]/page.tsx@@ -0,0 +1,61 @@+import type { Metadata } from "next";+import { headers } from "next/headers";+import { notFound } from "next/navigation";+import { connection } from "next/server";+import { cache, Suspense } from "react";+import { ChatSharePage } from "@/components/chat/share-page";+import { countsAsView } from "@/lib/share";+import { countShareView, findChatShare } from "@/server/chat/store";++/** The share, once per request (metadata and the page both read it). */+const load = cache((token: string) => findChatShare(token));++const PRIVATE: Metadata = {+ robots: { index: false, follow: false, nocache: true, googleBot: { index: false, follow: false, noimageindex: true } },+ referrer: "no-referrer",+};++async function requestBase(): Promise<URL | null> {+ const h = await headers();+ const host = h.get("x-forwarded-host")?.split(",")[0].trim() || h.get("host");+ const proto = h.get("x-forwarded-proto")?.split(",")[0].trim() === "https" ? "https" : "http";+ return host && /^[\w.-]+(:\d+)?$|^\[[\da-f:.]+\](:\d+)?$/i.test(host) ? new URL(`${proto}://${host}`) : null;+}++export async function generateMetadata({ params }: PageProps<"/c/[token]">): Promise<Metadata> {+ const { token } = await params;+ await connection();+ const s = load(token);+ if (!s) return { ...PRIVATE, title: { absolute: "Chat unavailable · Fuobe" } };+ const snap = s.snapshot;+ const title = snap.character ? `A chat with ${snap.character.name}` : snap.title;+ const first = snap.mature ? null : snap.messages.find((m) => m.role === "assistant")?.content.replace(/[*#_`>]/g, "").replace(/\s+/g, " ").slice(0, 160);+ const base = await requestBase();+ return {+ ...PRIVATE,+ ...(base && { metadataBase: base }),+ title: { absolute: `${title} · Fuobe` },+ description: first ?? "A chat shared from Fuobe.",+ openGraph: { title, description: first ?? undefined, type: "article" },+ twitter: { card: "summary_large_image", title },+ };+}++async function Content({ params }: { params: PageProps<"/c/[token]">["params"] }) {+ const { token } = await params;+ await connection();+ const s = load(token);+ if (!s) notFound();+ const h = await headers();+ if (countsAsView("GET", h)) countShareView(token);+ return <ChatSharePage token={token} snap={s.snapshot} portrait={!!s.portrait} />;+}++/** A shared chat's public page. The proxy lets /c/<token> through without a session; this page checks the token. */+export default function Page({ params }: PageProps<"/c/[token]">) {+ return (+ <Suspense fallback={<div className="min-h-svh bg-background" />}>+ <Content params={params} />+ </Suspense>+ );+}diff --git a/src/app/c/[token]/portrait/route.ts b/src/app/c/[token]/portrait/route.tsnew file mode 100644index 00000000..a21883ad--- /dev/null+++ b/src/app/c/[token]/portrait/route.ts@@ -0,0 +1,21 @@+import { connection } from "next/server";+import { readSharedPicture } from "@/server/chat/files";+import { findChatShare } from "@/server/chat/store";++/** A shared chat's character portrait: the one file a chat share shows, for anyone with the link. */+export async function GET(_request: Request, ctx: RouteContext<"/c/[token]/portrait">) {+ await connection();+ const { token } = await ctx.params;+ const s = findChatShare(token);+ const pic = s?.portrait ? await readSharedPicture(s.portrait) : null;+ if (!pic) return new Response("Not found", { status: 404, headers: { "Cache-Control": "no-store" } });+ return new Response(new Uint8Array(pic.data), {+ headers: {+ "Content-Type": pic.contentType,+ "Cache-Control": "public, max-age=300",+ "X-Content-Type-Options": "nosniff",+ "Content-Security-Policy": "default-src 'none'; sandbox",+ "Referrer-Policy": "no-referrer",+ },+ });+}diff --git a/src/components/chat/bits.tsx b/src/components/chat/bits.tsxnew file mode 100644index 00000000..e94c8124--- /dev/null+++ b/src/components/chat/bits.tsx@@ -0,0 +1,76 @@+"use client";++import { Drama, Gamepad2, Lightbulb, MessageCircle, PenLine } from "lucide-react";+import { useEffect, useState } from "react";+import type { ChatKind } from "@/lib/chat/catalog";+import type { ChatMe } from "@/lib/chat/types";+import { cn } from "@/lib/utils";++const KIND_ICON = { chat: MessageCircle, ideas: Lightbulb, write: PenLine, character: Drama, play: Gamepad2 } as const;++export function KindIcon({ kind, className }: { kind: ChatKind; className?: string }) {+ const Icon = KIND_ICON[kind] ?? MessageCircle;+ return <Icon className={cn("size-[18px]", className)} />;+}++/** Who answers, in a few words: Fuobe's free model (ready or busy) or the person's own key. */+export function EngineLine({ me, className }: { me: ChatMe | undefined; className?: string }) {+ if (!me) return null;+ const key = me.engine === "key" && me.key;+ const short = key ? me.key!.model.split("/").pop()!.replace(/:free$/, "") : null;+ return (+ <span className={cn("inline-flex min-w-0 items-center gap-1.5 px-1 text-[12.5px] text-muted-foreground", className)}>+ <span className={cn("size-1.5 shrink-0 rounded-full", key || me.site ? "bg-emerald-500" : "bg-amber-500")} aria-hidden />+ <span className="truncate">{key ? `Your key · ${short}` : me.site ? "Free model" : me.siteKnown ? "Free model · busy right now" : "Free model · resting"}</span>+ </span>+ );+}++export function timeAgo(t: number, now = Date.now()): string {+ const s = Math.max(0, Math.round((now - t) / 1000));+ if (s < 60) return "now";+ const m = Math.round(s / 60);+ if (m < 60) return `${m} min`;+ const h = Math.round(m / 60);+ if (h < 24) return `${h} h`;+ const d = Math.round(h / 24);+ if (d < 7) return `${d} d`;+ return new Date(t).toLocaleDateString(undefined, { day: "numeric", month: "short" });+}++/** Three soft dots while a reply is on its way (the words are for screen readers). */+export function TypingDots({ label }: { label: string }) {+ return (+ <span className="flex h-4 items-center gap-1.5 text-muted-foreground" role="status">+ {[0, 1, 2].map((i) => (+ <span key={i} className="size-2 animate-bounce rounded-full bg-current opacity-70 motion-reduce:animate-none" style={{ animationDelay: `${i * 150}ms`, animationDuration: "1.1s" }} aria-hidden />+ ))}+ <span className="sr-only">{label}…</span>+ </span>+ );+}++/**+ * A reply that arrived all at once, shown as if written: quick, by word, never longer than about a second and a half.+ * With reduced motion it shows at once.+ */+export function useReveal(text: string, on: boolean): string {+ // Decided when the message first shows: a reply that arrived whole starts empty, every other shows in full.+ const [n, setN] = useState(() => (on && typeof window !== "undefined" && !window.matchMedia("(prefers-reduced-motion: reduce)").matches ? 0 : Number.POSITIVE_INFINITY));+ const revealing = n < text.length;+ useEffect(() => {+ if (!revealing) return;+ const step = Math.max(3, Math.ceil(text.length / 90));+ const id = window.setInterval(() => {+ setN((x) => {+ if (x >= text.length) return Number.POSITIVE_INFINITY;+ // Stop at the end of a word so letters don't flicker.+ let next = Math.min(text.length, x + step);+ while (next < text.length && !/\s/.test(text[next])) next++;+ return next;+ });+ }, 16);+ return () => window.clearInterval(id);+ }, [revealing, text]);+ return revealing ? text.slice(0, n) : text;+}diff --git a/src/components/chat/character-builder.tsx b/src/components/chat/character-builder.tsxnew file mode 100644index 00000000..5f0231a7--- /dev/null+++ b/src/components/chat/character-builder.tsx@@ -0,0 +1,251 @@+"use client";++import { useQueryClient } from "@tanstack/react-query";+import { ImagePlus, Loader2, Sparkles, Trash2, X } from "lucide-react";+import Link from "next/link";+import { useRef, useState } from "react";+import { Button } from "@/components/ui/button";+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";+import { Input } from "@/components/ui/input";+import { Textarea } from "@/components/ui/textarea";+import { uploadFile } from "@/lib/api";+import { CHAT_LIMITS, MANGO_CHILLI, type CharacterCard } from "@/lib/chat/catalog";+import { toastError } from "@/lib/refusals";+import { cn } from "@/lib/utils";+import { CharacterFace } from "./character-face";+import { ChilliDot } from "./dialogs";+import { chatSend } from "./hooks";++const PALETTES: [string, string][] = [+ ["#241a3a", "#6a5ee7"],+ ["#2a0f1e", "#d4567c"],+ ["#0d1b2a", "#3a86ff"],+ ["#3b2a20", "#e0a458"],+ ["#10261c", "#3fb68b"],+ ["#1c1c1c", "#8a7650"],+ ["#1a0508", "#a4161a"],+ ["#0b3954", "#ff8552"],+];++interface Draft {+ name: string;+ tagline: string;+ persona: string;+ scenario: string;+ greeting: string;+ mature: boolean;+ accent: [string, string];+ portrait: string | null;+}++const EMPTY: Draft = { name: "", tagline: "", persona: "", scenario: "", greeting: "", mature: false, accent: PALETTES[0], portrait: null };++/** A portrait prompt for the Image studio from what the person wrote. */+const portraitPrompt = (d: Draft) =>+ `Editorial portrait of ${d.name || "a character"}${d.tagline ? `, ${d.tagline}` : ""}. ${d.persona.slice(0, 300)} Head-and-shoulders, 3:4 vertical, cinematic soft key light, shallow depth of field, rich colour, fashion magazine quality.`;++interface BuilderProps {+ open: boolean;+ onOpenChange: (o: boolean) => void;+ editing?: CharacterCard | null;+ mature: boolean;+ onSaved?: (c: CharacterCard, start: boolean) => void;+}++/** Make or change a character: their look, who they are, where the story starts and their first line. */+export function CharacterBuilder(props: BuilderProps) {+ return (+ <Dialog open={props.open} onOpenChange={props.onOpenChange}>+ <DialogContent className="max-h-[94svh] overflow-y-auto sm:max-w-[640px]">+ {/* Made fresh each time it opens, from the character being edited or blank. */}+ {props.open && <BuilderBody key={props.editing?.id ?? "new"} {...props} />}+ </DialogContent>+ </Dialog>+ );+}++function BuilderBody({ onOpenChange, editing, mature, onSaved }: BuilderProps) {+ const qc = useQueryClient();+ const [d, setD] = useState<Draft>(() =>+ editing ? { name: editing.name, tagline: editing.tagline, persona: editing.persona, scenario: editing.scenario, greeting: editing.greeting, mature: editing.mature, accent: editing.accent, portrait: editing.portrait } : EMPTY,+ );+ const [preview, setPreview] = useState<string | null>(null);+ const [uploading, setUploading] = useState(false);+ const [busy, setBusy] = useState<string | null>(null);+ const file = useRef<HTMLInputElement>(null);++ const add = async (f: File | undefined) => {+ if (!f) return;+ setPreview(URL.createObjectURL(f));+ setUploading(true);+ try {+ const a = await uploadFile(f);+ setD((x) => ({ ...x, portrait: a.url }));+ } catch (e) {+ setPreview(null);+ toastError(e, "That picture couldn't be added.");+ } finally {+ setUploading(false);+ }+ };++ const ready = d.name.trim().length > 0 && d.persona.trim().length >= 10 && !uploading;++ const save = async (start: boolean) => {+ setBusy(start ? "start" : "save");+ try {+ const c = editing+ ? await chatSend<CharacterCard>(`/api/chat/characters/${editing.id}`, "PATCH", d)+ : await chatSend<CharacterCard>("/api/chat/characters", "POST", d);+ void qc.invalidateQueries({ queryKey: ["chat", "characters"] });+ onOpenChange(false);+ onSaved?.(c, start);+ } catch (e) {+ toastError(e);+ } finally {+ setBusy(null);+ }+ };++ const remove = async () => {+ if (!editing) return;+ setBusy("delete");+ try {+ await chatSend(`/api/chat/characters/${editing.id}`, "DELETE");+ void qc.invalidateQueries({ queryKey: ["chat", "characters"] });+ onOpenChange(false);+ } catch (e) {+ toastError(e);+ } finally {+ setBusy(null);+ }+ };++ const field = "text-[13px] font-medium";+ return (+ <>+ <DialogHeader>+ <DialogTitle>{editing ? `Edit ${editing.name}` : "New character"}</DialogTitle>+ <DialogDescription>Characters stay in role, remember the story and move it forward. Every character is a fictional adult.</DialogDescription>+ </DialogHeader>+ <div className="grid gap-5 sm:grid-cols-[180px_minmax(0,1fr)]">+ <div className="space-y-2.5">+ <input ref={file} type="file" accept="image/png,image/jpeg,image/webp" className="hidden" onChange={(e) => void add(e.target.files?.[0])} />+ <button type="button" onClick={() => file.current?.click()} className="group relative block w-full" aria-label="Add a portrait">+ <CharacterFace name={d.name || "?"} accent={d.accent} portrait={preview ?? d.portrait} rounded="card" className="aspect-[3/4] w-full" />+ <span className="absolute inset-x-2 bottom-2 flex items-center justify-center gap-1.5 rounded-full bg-black/55 py-1.5 text-[12px] font-medium text-white opacity-90 backdrop-blur-sm group-hover:opacity-100">+ {uploading ? <Loader2 className="size-3.5 animate-spin" /> : <ImagePlus className="size-3.5" />}+ {d.portrait ? "Change portrait" : "Add a portrait"}+ </span>+ </button>+ {d.portrait && (+ <button+ type="button"+ onClick={() => {+ setD({ ...d, portrait: null });+ setPreview(null);+ }}+ className="flex w-full items-center justify-center gap-1 text-[12px] text-muted-foreground hover:text-foreground"+ >+ <X className="size-3" /> Remove portrait+ </button>+ )}+ <Link+ href={`/image?prompt=${encodeURIComponent(portraitPrompt(d))}&format=3:4`}+ target="_blank"+ className="flex items-center justify-center gap-1.5 rounded-full border py-1.5 text-[12.5px] hover:bg-accent"+ >+ <Sparkles className="size-3.5" />+ Make one in Image+ </Link>+ <div className="flex flex-wrap justify-center gap-1.5 pt-1" role="radiogroup" aria-label="Colours">+ {PALETTES.map((p) => {+ const on = p[0] === d.accent[0] && p[1] === d.accent[1];+ return (+ <button+ key={p.join()}+ type="button"+ role="radio"+ aria-checked={on}+ aria-label={`Colours ${p.join(" and ")}`}+ onClick={() => setD({ ...d, accent: p })}+ className={cn("size-6 rounded-full ring-offset-2 ring-offset-background", on && "ring-2 ring-foreground")}+ style={{ background: `linear-gradient(145deg, ${p[0]}, ${p[1]})` }}+ />+ );+ })}+ </div>+ </div>+ <div className="min-w-0 space-y-3.5">+ <div className="grid gap-3.5 sm:grid-cols-2">+ <label className="block space-y-1.5">+ <span className={field}>Name</span>+ <Input value={d.name} onChange={(e) => setD({ ...d, name: e.target.value })} placeholder="Aurelie Blanc" maxLength={CHAT_LIMITS.nameChars} autoFocus />+ </label>+ <label className="block space-y-1.5">+ <span className={field}>One line about them</span>+ <Input value={d.tagline} onChange={(e) => setD({ ...d, tagline: e.target.value })} placeholder="Perfumer with a secret" maxLength={CHAT_LIMITS.taglineChars} />+ </label>+ </div>+ <label className="block space-y-1.5">+ <span className={field}>Who they are and how they talk</span>+ <Textarea+ value={d.persona}+ onChange={(e) => setD({ ...d, persona: e.target.value })}+ placeholder="34, runs a tiny perfume house in Grasse. Precise, warm, a little mischievous. Describes everything by its scent."+ rows={3}+ maxLength={CHAT_LIMITS.personaChars}+ />+ </label>+ <label className="block space-y-1.5">+ <span className={field}>+ Where the story starts <span className="font-normal text-muted-foreground">(optional)</span>+ </span>+ <Textarea+ value={d.scenario}+ onChange={(e) => setD({ ...d, scenario: e.target.value })}+ placeholder="You walk into her shop just before closing, looking for a gift."+ rows={2}+ maxLength={CHAT_LIMITS.scenarioChars}+ />+ </label>+ <label className="block space-y-1.5">+ <span className={field}>+ Their first line <span className="font-normal text-muted-foreground">(optional)</span>+ </span>+ <Textarea+ value={d.greeting}+ onChange={(e) => setD({ ...d, greeting: e.target.value })}+ placeholder="*looks up from a row of tiny bottles* We're closing, but… you have the face of someone looking for something rare."+ rows={2}+ maxLength={CHAT_LIMITS.greetingChars}+ />+ </label>+ {mature && (+ <label className="flex cursor-pointer items-center gap-2.5 rounded-xl border p-2.5 text-[13.5px]">+ <input type="checkbox" checked={d.mature} onChange={(e) => setD({ ...d, mature: e.target.checked })} className="size-4 accent-[#ff6a2b]" />+ <ChilliDot />+ <span>{MANGO_CHILLI.short} character (only shows while the mode is on)</span>+ </label>+ )}+ </div>+ </div>+ <DialogFooter className="items-center gap-2">+ {editing && (+ <Button variant="ghost" onClick={() => void remove()} disabled={!!busy} className="mr-auto text-muted-foreground">+ {busy === "delete" ? <Loader2 className="animate-spin" /> : <Trash2 />}+ Delete+ </Button>+ )}+ <Button variant="secondary" onClick={() => void save(false)} disabled={!ready || !!busy}>+ {busy === "save" && <Loader2 className="animate-spin" />}+ Save+ </Button>+ <Button onClick={() => void save(true)} disabled={!ready || !!busy}>+ {busy === "start" && <Loader2 className="animate-spin" />}+ Save and chat+ </Button>+ </DialogFooter>+ </>+ );+}diff --git a/src/components/chat/character-face.tsx b/src/components/chat/character-face.tsxnew file mode 100644index 00000000..f849c695--- /dev/null+++ b/src/components/chat/character-face.tsx@@ -0,0 +1,39 @@+import { cn } from "@/lib/utils";++/**+ * A character's face: their portrait, or their initial on their own two colours. `src` overrides where the portrait+ * comes from (a shared chat serves it from its own link).+ */+export function CharacterFace({+ name,+ accent,+ portrait,+ src,+ className,+ rounded = "full",+}: {+ name: string;+ accent: [string, string];+ portrait?: string | null;+ src?: string | null;+ className?: string;+ rounded?: "full" | "card";+}) {+ const url = src ?? portrait ?? null;+ return (+ <span+ className={cn("relative grid shrink-0 place-items-center overflow-hidden text-white select-none", rounded === "full" ? "rounded-full" : "rounded-[18px]", className)}+ style={{ background: `linear-gradient(145deg, ${accent[0]} 0%, ${accent[1]} 100%)`, containerType: "inline-size" }}+ aria-hidden+ >+ {url ? (+ // eslint-disable-next-line @next/next/no-img-element+ <img src={url} alt="" className="absolute inset-0 size-full object-cover" loading="lazy" />+ ) : (+ <span className="font-heading leading-none" style={{ fontSize: "min(44cqw, 6rem)" }}>+ {name.slice(0, 1).toUpperCase()}+ </span>+ )}+ </span>+ );+}diff --git a/src/components/chat/chat-home.tsx b/src/components/chat/chat-home.tsxnew file mode 100644index 00000000..27566c69--- /dev/null+++ b/src/components/chat/chat-home.tsx@@ -0,0 +1,385 @@+"use client";++import { useQueryClient } from "@tanstack/react-query";+import { Pencil, Plus, Settings2 } from "lucide-react";+import Link from "next/link";+import { useRouter, useSearchParams } from "next/navigation";+import { useEffect, useMemo, useRef, useState } from "react";+import { toast } from "sonner";+import { PhoneNavButton } from "@/components/nav/phone-nav-button";+import { Button } from "@/components/ui/button";+import { Skeleton } from "@/components/ui/skeleton";+import { TAB_PILL, TabRow, onAttr } from "@/components/ui/tab-row";+import { askToSignUp, useHydrated, useIsGuest, useViewer } from "@/lib/api";+import { BUILT_IN_CHARACTERS, CHAT_KINDS, isChatKind, MANGO_CHILLI, PLAY_FORMATS, STARTERS, WRITE_TOOLS, playFormat, writeTool, type CharacterCard, type ChatKind, type PlayFormat, type WriteTool } from "@/lib/chat/catalog";+import { playMessage, toolMessage } from "@/lib/chat/prompt";+import type { ChatThreadSummary } from "@/lib/chat/types";+import { toastError } from "@/lib/refusals";+import { cn } from "@/lib/utils";+import { CharacterBuilder } from "./character-builder";+import { CharacterFace } from "./character-face";+import { ChatComposer } from "./composer";+import { ChatSettingsDialog, ChilliDot, CHILLI_BG, MangoChilliDialog, PlayDialog, WriteToolDialog } from "./dialogs";+import { chatSend, useCharacters, useChatMe, useChatThreads, useStartChat } from "./hooks";+import { EngineLine, KindIcon, timeAgo } from "./bits";++/**+ * Fuobe Chat's home: one box to start talking, the kinds of chat (Chat, Ideas, Write, Characters, Play), the+ * characters, and recent chats. A guest sees all of it; starting anything opens the sign-up card.+ */+export function ChatHome() {+ const router = useRouter();+ const sp = useSearchParams();+ const qc = useQueryClient();+ const viewer = useViewer();+ const guest = useIsGuest();+ // Until the page has hydrated it reads as unknown, so the first render matches the server's HTML even when the+ // viewer is already cached (the nav reads it too).+ const hydrated = useHydrated();+ const known = hydrated && viewer.isSuccess;+ const signedIn = known && !guest;+ const me = useChatMe(signedIn);+ const threads = useChatThreads(signedIn);+ const characters = useCharacters(signedIn);+ const start = useStartChat();++ // A link can open a kind, a writing tool or a game with its form (?kind=, ?tool=, ?play=).+ const [kind, setKind] = useState<ChatKind>(() => {+ const k = sp.get("kind");+ return playFormat(sp.get("play")) ? "play" : writeTool(sp.get("tool")) ? "write" : isChatKind(k) ? k : "chat";+ });+ const [tool, setTool] = useState<WriteTool | null>(() => writeTool(sp.get("tool")));+ const [play, setPlay] = useState<PlayFormat | null>(() => {+ const p = playFormat(sp.get("play"));+ return p && (p.ask || p.picture) ? p : null;+ });+ const [building, setBuilding] = useState<{ open: boolean; editing: CharacterCard | null }>({ open: false, editing: null });+ const [settings, setSettings] = useState(false);+ const [chilli, setChilli] = useState(false);+ const [starting, setStarting] = useState(false);+ const mature = !!me.data?.mature;++ const gate = () => {+ if (guest) {+ askToSignUp("run");+ return false;+ }+ return signedIn;+ };++ const go = async (s: Parameters<typeof start>[0]) => {+ if (!gate()) return;+ setStarting(true);+ try {+ const t = await start(s);+ router.push(`/chat/${t.id}`);+ } catch (e) {+ if ((e as { code?: string }).code === "mature-off") setChilli(true);+ else toastError(e);+ setStarting(false);+ }+ };++ // Links that start a chat at once: ?character=, a game with nothing to fill in, and ?from=<shared chat> ("Chat with them").+ const handled = useRef(false);+ useEffect(() => {+ if (handled.current || !known) return;+ const character = sp.get("character");+ const from = sp.get("from");+ const p = playFormat(sp.get("play"));+ const now = p && !p.ask && !p.picture ? p : null;+ if (!character && !from && !now) return;+ handled.current = true;+ if (guest) {+ askToSignUp("run");+ return;+ }+ // A link's one-time start: it shows the button busy while the chat is made.+ // eslint-disable-next-line react-hooks/set-state-in-effect+ if (now) void go({ kind: "play", play: now.id, text: playMessage(now.id, "") });+ else if (character) void go({ kind: "character", characterId: character });+ else if (from) {+ chatSend<CharacterCard>("/api/chat/characters", "POST", { fromShare: from })+ .then((c) => {+ void qc.invalidateQueries({ queryKey: ["chat", "characters"] });+ return go({ kind: "character", characterId: c.id });+ })+ .catch((e) => ((e as { code?: string }).code === "mature-off" ? setChilli(true) : toastError(e)));+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [known, guest]);++ const cast = useMemo(() => (signedIn ? (characters.data?.items ?? null) : BUILT_IN_CHARACTERS.filter((c) => !c.mature)), [signedIn, characters.data]);+ const k = CHAT_KINDS.find((x) => x.id === kind)!;+ const typing = kind === "chat" || kind === "ideas" || kind === "write";++ return (+ <div className="flex h-content min-w-0 flex-col">+ <header className="flex h-14 shrink-0 items-center gap-1.5 px-4 sm:px-6">+ <Link href="/chat" className="font-heading text-[22px] leading-none">+ Chat+ </Link>+ <div className="flex-1" />+ {signedIn && (+ <>+ <button+ type="button"+ onClick={() => (mature ? setSettings(true) : setChilli(true))}+ className={cn(+ "inline-flex h-9 items-center gap-2 rounded-full border px-3 text-[13px] font-medium transition-colors",+ mature ? "border-transparent text-white " + CHILLI_BG : "text-muted-foreground hover:bg-accent hover:text-foreground",+ )}+ aria-pressed={mature}+ title={mature ? `${MANGO_CHILLI.name} is on` : `Turn on ${MANGO_CHILLI.name}`}+ >+ {!mature && <ChilliDot />}+ {MANGO_CHILLI.short}+ </button>+ <Button variant="ghost" size="icon" onClick={() => setSettings(true)} aria-label="Chat settings">+ <Settings2 />+ </Button>+ </>+ )}+ <PhoneNavButton />+ </header>++ <div className="min-h-0 flex-1 overflow-y-auto px-4 sm:px-6">+ <div className="mx-auto w-full max-w-[880px] pt-[6vh] pb-20 sm:pt-[9vh]">+ <h1 className="font-heading text-[clamp(40px,7vw,64px)] leading-[1.02] tracking-[-0.01em] text-balance">{mature ? "Say what you really mean." : "Talk it through."}</h1>+ <p className="mt-3 max-w-[56ch] text-[15.5px] text-pretty text-muted-foreground">+ Ask anything, brainstorm ideas you can make in one tap, write captions and scripts, or step into a story with a character. Free on Fuobe.+ </p>++ <TabRow role="tablist" aria-label="Kind of chat" className="mt-8 w-fit max-w-full">+ {CHAT_KINDS.map((x) => (+ <button key={x.id} role="tab" aria-selected={x.id === kind} className={TAB_PILL} {...onAttr(x.id === kind)} onClick={() => setKind(x.id)}>+ {x.label}+ </button>+ ))}+ </TabRow>++ {typing && (+ <div className="mt-4">+ <ChatComposer+ key={kind}+ large+ autoFocus={signedIn}+ mature={mature}+ placeholder={k.placeholder}+ disabled={starting}+ busy={starting}+ onSend={(text, image) => go({ kind, text, image })}+ footer={signedIn ? <EngineLine me={me.data} /> : guest ? <span className="px-1 text-[12.5px] text-muted-foreground">Free with an account</span> : null}+ />+ </div>+ )}++ <section className="mt-6">+ {kind === "chat" || kind === "ideas" ? (+ <div className="grid gap-x-6 sm:grid-cols-2">+ {STARTERS[kind].map((s) => (+ <button+ key={s}+ type="button"+ onClick={() => void go({ kind, text: s })}+ className="group flex items-baseline gap-3 border-b py-3 text-left text-[15px] text-muted-foreground transition-colors hover:text-foreground"+ >+ <span className="text-subtle-foreground transition-colors group-hover:text-brand-text" aria-hidden>+ {kind === "ideas" ? "✦" : "›"}+ </span>+ {s}+ </button>+ ))}+ </div>+ ) : kind === "write" ? (+ <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">+ {WRITE_TOOLS.map((t) => (+ <button+ key={t.id}+ type="button"+ onClick={() => gate() && setTool(t)}+ className="rounded-2xl border bg-background p-4 text-left transition-[border-color,box-shadow] hover:border-primary hover:shadow-soft focus-visible:ring-4 focus-visible:ring-brand-faint focus-visible:outline-none"+ >+ <span className="font-heading text-[21px] leading-none">{t.name}</span>+ <span className="mt-1.5 block text-[13.5px] text-muted-foreground">{t.blurb}</span>+ </button>+ ))}+ </div>+ ) : kind === "play" ? (+ <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">+ {PLAY_FORMATS.map((p) => (+ <button+ key={p.id}+ type="button"+ onClick={() => {+ if (!gate()) return;+ if (p.ask || p.picture) setPlay(p);+ else void go({ kind: "play", play: p.id, text: playMessage(p.id, "") });+ }}+ className="flex items-start gap-3 rounded-2xl border bg-background p-4 text-left transition-[border-color,box-shadow] hover:border-primary hover:shadow-soft focus-visible:ring-4 focus-visible:ring-brand-faint focus-visible:outline-none"+ >+ <span className="text-[26px] leading-none" aria-hidden>+ {p.emoji}+ </span>+ <span className="min-w-0">+ <span className="block text-[15px] font-medium">{p.name}</span>+ <span className="mt-0.5 block text-[13.5px] text-muted-foreground">{p.blurb}</span>+ </span>+ </button>+ ))}+ </div>+ ) : null}+ </section>++ {(kind === "character" || kind === "chat") && (+ <section className="mt-12">+ <div className="mb-4 flex items-end justify-between gap-3">+ <h2 className="font-heading text-[28px] leading-none">Characters</h2>+ {kind === "chat" && (+ <button type="button" onClick={() => setKind("character")} className="text-[13px] text-muted-foreground hover:text-foreground">+ See all+ </button>+ )}+ </div>+ <CharacterShelf+ cast={cast}+ row={kind === "chat"}+ onPick={(c) => void go({ kind: "character", characterId: c.id })}+ onEdit={(c) => setBuilding({ open: true, editing: c })}+ onNew={() => gate() && setBuilding({ open: true, editing: null })}+ />+ </section>+ )}++ {signedIn && <Recent threads={threads.data?.items} loading={threads.isPending} />}+ </div>+ </div>++ <WriteToolDialog+ tool={tool}+ onOpenChange={(o) => !o && setTool(null)}+ onStart={async (values, tone) => {+ if (!tool) return;+ await go({ kind: "write", tool: tool.id, text: toolMessage(tool.id, values, tone) });+ }}+ />+ <PlayDialog play={play} onOpenChange={(o) => !o && setPlay(null)} onStart={async (input, image) => (play ? go({ kind: "play", play: play.id, text: playMessage(play.id, input), image }) : undefined)} />+ <CharacterBuilder+ open={building.open}+ editing={building.editing}+ mature={mature}+ onOpenChange={(o) => setBuilding((b) => ({ ...b, open: o }))}+ onSaved={(c, startNow) => {+ if (startNow) void go({ kind: "character", characterId: c.id });+ else toast.success(`${c.name} is saved.`);+ }}+ />+ <ChatSettingsDialog open={settings} onOpenChange={setSettings} me={me.data} />+ <MangoChilliDialog open={chilli} onOpenChange={setChilli} />+ </div>+ );+}++function CharacterShelf({+ cast,+ row,+ onPick,+ onEdit,+ onNew,+}: {+ cast: CharacterCard[] | null;+ row: boolean;+ onPick: (c: CharacterCard) => void;+ onEdit: (c: CharacterCard) => void;+ onNew: () => void;+}) {+ const shown = cast ? (row ? cast.slice(0, 5) : cast) : null;+ return (+ <div className={cn(row ? "scrollbar-none -mx-4 flex snap-x gap-3 overflow-x-auto px-4 pb-2 sm:mx-0 sm:grid sm:grid-cols-5 sm:overflow-visible sm:px-0" : "grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4")}>+ <button+ type="button"+ onClick={onNew}+ className={cn(+ "grid aspect-[3/4] shrink-0 snap-start place-items-center rounded-[18px] border border-dashed text-muted-foreground transition-colors hover:border-primary hover:text-foreground",+ row && "w-[42vw] max-w-[180px] sm:w-auto sm:max-w-none",+ )}+ >+ <span className="flex flex-col items-center gap-2 text-[14px]">+ <Plus className="size-5" />+ New character+ </span>+ </button>+ {shown+ ? shown.map((c) => (+ <div key={c.id} className={cn("group relative shrink-0 snap-start", row && "w-[42vw] max-w-[180px] sm:w-auto sm:max-w-none")}>+ <button type="button" onClick={() => onPick(c)} className="block w-full text-left focus-visible:outline-none" aria-label={`Chat with ${c.name}`}>+ <CharacterFace name={c.name} accent={c.accent} portrait={c.portrait} rounded="card" className="aspect-[3/4] w-full transition-transform duration-300 group-hover:scale-[1.015] group-focus-visible:ring-4 group-focus-visible:ring-brand-faint" />+ <span className="pointer-events-none absolute inset-x-0 bottom-0 rounded-b-[18px] bg-gradient-to-t from-black/80 via-black/40 to-transparent p-3 pt-10 text-white">+ <span className="flex items-center gap-1.5">+ <span className="font-heading text-[20px] leading-tight">{c.name}</span>+ {c.mature && <ChilliDot className="size-2" />}+ </span>+ <span className="mt-0.5 line-clamp-2 block text-[12px] leading-snug text-white/80">{c.tagline}</span>+ </span>+ </button>+ {!c.builtIn && (+ <button+ type="button"+ onClick={() => onEdit(c)}+ className="absolute top-2 right-2 grid size-8 place-items-center rounded-full bg-black/45 text-white opacity-0 backdrop-blur-sm transition-opacity group-hover:opacity-100 focus-visible:opacity-100"+ aria-label={`Edit ${c.name}`}+ >+ <Pencil className="size-3.5" />+ </button>+ )}+ </div>+ ))+ : Array.from({ length: row ? 4 : 7 }, (_, i) => <Skeleton key={i} className={cn("aspect-[3/4] shrink-0 rounded-[18px]", row && "w-[42vw] max-w-[180px] sm:w-auto")} />)}+ </div>+ );+}++function Recent({ threads, loading }: { threads: ChatThreadSummary[] | undefined; loading: boolean }) {+ const [all, setAll] = useState(false);+ if (!loading && !threads?.length) return null;+ const more = (threads?.length ?? 0) - 12;+ return (+ <section className="mt-12">+ <h2 className="mb-2 font-heading text-[28px] leading-none">Recent</h2>+ <ul className="divide-y">+ {loading+ ? Array.from({ length: 3 }, (_, i) => (+ <li key={i} className="py-3">+ <Skeleton className="h-10 w-full" />+ </li>+ ))+ : threads!.slice(0, all ? undefined : 12).map((t) => (+ <li key={t.id}>+ <Link href={`/chat/${t.id}`} className="group flex items-center gap-3 py-3">+ {t.character ? (+ <CharacterFace name={t.character.name} accent={t.character.accent} portrait={t.character.portrait} className="size-10" />+ ) : (+ <span className="grid size-10 shrink-0 place-items-center rounded-full bg-muted text-muted-foreground">+ <KindIcon kind={t.kind} />+ </span>+ )}+ <span className="min-w-0 flex-1">+ <span className="flex items-center gap-1.5">+ <span className="truncate text-[15px] font-medium group-hover:text-brand-text">{t.title}</span>+ {t.mature && <ChilliDot className="size-2" />}+ </span>+ <span className="block truncate text-[13px] text-muted-foreground">{t.preview || " "}</span>+ </span>+ <span className="shrink-0 text-[12px] text-subtle-foreground">{timeAgo(t.updatedAt)}</span>+ </Link>+ </li>+ ))}+ </ul>+ {!loading && !all && more > 0 && (+ <Button variant="ghost" size="sm" className="mt-2 text-muted-foreground" onClick={() => setAll(true)}>+ Show {more} more+ </Button>+ )}+ </section>+ );+}diff --git a/src/components/chat/composer.tsx b/src/components/chat/composer.tsxnew file mode 100644index 00000000..9cd82d39--- /dev/null+++ b/src/components/chat/composer.tsx@@ -0,0 +1,174 @@+"use client";++import { ArrowUp, ImagePlus, Loader2, Square, X } from "lucide-react";+import { forwardRef, useImperativeHandle, useRef, useState, type ReactNode } from "react";+import { Button } from "@/components/ui/button";+import { uploadFile } from "@/lib/api";+import { CHAT_LIMITS } from "@/lib/chat/catalog";+import { toastError } from "@/lib/refusals";+import { cn } from "@/lib/utils";++export interface ComposerHandle {+ focus: () => void;+ set: (text: string) => void;+}++/**+ * Fuobe Chat's message box: Enter sends, Shift+Enter starts a new line, one picture can go with a message (picked,+ * pasted or dropped). While a reply is written the send button stops it.+ */+export const ChatComposer = forwardRef<+ ComposerHandle,+ {+ onSend: (text: string, image: string | null) => void | Promise<void>;+ onStop?: () => void;+ busy?: boolean;+ disabled?: boolean;+ placeholder: string;+ pictures?: boolean;+ autoFocus?: boolean;+ footer?: ReactNode;+ large?: boolean;+ mature?: boolean;+ }+>(function ChatComposer({ onSend, onStop, busy, disabled, placeholder, pictures = true, autoFocus, footer, large, mature }, ref) {+ const [text, setText] = useState("");+ const [image, setImage] = useState<{ preview: string; url?: string } | null>(null);+ const input = useRef<HTMLTextAreaElement>(null);+ const file = useRef<HTMLInputElement>(null);++ useImperativeHandle(ref, () => ({+ focus: () => input.current?.focus(),+ set: (t: string) => {+ setText(t);+ requestAnimationFrame(() => {+ const el = input.current;+ if (!el) return;+ el.focus();+ el.setSelectionRange(t.length, t.length);+ });+ },+ }));++ const add = async (f: File | undefined) => {+ if (!f || !/^image\/(png|jpeg|webp|gif)$/.test(f.type)) return;+ const preview = URL.createObjectURL(f);+ setImage({ preview });+ try {+ const a = await uploadFile(f);+ setImage((cur) => (cur?.preview === preview ? { preview, url: a.url } : cur));+ } catch (e) {+ setImage(null);+ toastError(e, "That picture couldn't be added.");+ }+ };++ const uploading = !!image && !image.url;+ const ready = !disabled && !busy && !uploading && (text.trim().length > 0 || !!image?.url);++ const send = async () => {+ if (!ready) return;+ const t = text.trim();+ const img = image?.url ?? null;+ setText("");+ setImage(null);+ await onSend(t, img);+ };++ return (+ <div+ className={cn(+ "relative rounded-[22px] border bg-background p-2 shadow-soft transition-[border-color,box-shadow] focus-within:border-primary focus-within:ring-4 focus-within:ring-brand-faint sm:rounded-composer",+ mature && "focus-within:border-[#e8572b] focus-within:ring-[#ff8a3d]/20",+ )}+ onDragOver={(e) => pictures && e.preventDefault()}+ onDrop={(e) => {+ if (!pictures) return;+ e.preventDefault();+ void add(e.dataTransfer.files[0]);+ }}+ >+ {image && (+ <div className="px-2 pt-1.5 pb-1">+ <div className="relative size-16 overflow-hidden rounded-xl border bg-muted">+ {/* eslint-disable-next-line @next/next/no-img-element */}+ <img src={image.preview} alt="" className="size-full object-cover" />+ {uploading && <Loader2 className="absolute inset-0 m-auto size-4 animate-spin text-white drop-shadow" />}+ <button type="button" onClick={() => setImage(null)} className="absolute top-1 right-1 grid size-5 place-items-center rounded-full bg-black/70 text-white" aria-label="Remove picture">+ <X className="size-3" />+ </button>+ </div>+ </div>+ )}+ <textarea+ ref={input}+ value={text}+ autoFocus={autoFocus}+ maxLength={CHAT_LIMITS.messageChars}+ onChange={(e) => setText(e.target.value)}+ onPaste={(e) => {+ const f = pictures ? [...e.clipboardData.files].find((x) => x.type.startsWith("image/")) : undefined;+ if (f) {+ e.preventDefault();+ void add(f);+ }+ }}+ onKeyDown={(e) => {+ if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) {+ e.preventDefault();+ void send();+ }+ }}+ placeholder={placeholder}+ rows={1}+ aria-label="Message"+ className={cn(+ "field-sizing-content max-h-56 w-full resize-none bg-transparent px-3 py-2 leading-relaxed outline-none placeholder:text-subtle-foreground",+ large ? "min-h-16 text-[17px]" : "min-h-11 text-base",+ )}+ />+ <div className="flex items-center gap-1.5 px-1">+ {pictures && (+ <>+ <input+ ref={file}+ type="file"+ accept="image/png,image/jpeg,image/webp,image/gif"+ className="hidden"+ onChange={(e) => {+ void add(e.target.files?.[0]);+ e.target.value = "";+ }}+ />+ <button+ type="button"+ onClick={() => file.current?.click()}+ disabled={disabled || busy}+ className="grid size-9 place-items-center rounded-full text-muted-foreground hover:bg-accent hover:text-foreground disabled:opacity-50"+ aria-label="Add a picture"+ title="Add a picture"+ >+ <ImagePlus className="size-[18px]" />+ </button>+ </>+ )}+ <div className="min-w-0 flex-1">{footer}</div>+ {busy && onStop ? (+ <Button size="icon" variant="secondary" className="size-10 shrink-0 rounded-full" onClick={onStop} aria-label="Stop the reply">+ <Square className="size-3.5 fill-current" />+ </Button>+ ) : (+ <Button+ size="icon"+ className={cn("size-10 shrink-0 rounded-full", mature && "bg-[linear-gradient(135deg,#ffb020,#e8352b)] text-white hover:opacity-90")}+ disabled={!ready}+ onClick={() => void send()}+ aria-label="Send"+ >+ {uploading ? <Loader2 className="animate-spin" /> : <ArrowUp />}+ </Button>+ )}+ </div>+ </div>+ );+});diff --git a/src/components/chat/dialogs.tsx b/src/components/chat/dialogs.tsxnew file mode 100644index 00000000..d3b21632--- /dev/null+++ b/src/components/chat/dialogs.tsx@@ -0,0 +1,551 @@+"use client";++import { useQueryClient } from "@tanstack/react-query";+import { Check, Copy, Download, ImagePlus, KeyRound, Link2, Link2Off, Loader2, Trash2 } from "lucide-react";+import { useRef, useState } from "react";+import { toast } from "sonner";+import { Button } from "@/components/ui/button";+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";+import { Input } from "@/components/ui/input";+import { Switch } from "@/components/ui/switch";+import { Textarea } from "@/components/ui/textarea";+import { TAB_PILL, TabRow, onAttr } from "@/components/ui/tab-row";+import { uploadFile } from "@/lib/api";+import { MANGO_CHILLI, type PlayFormat, type WriteTool } from "@/lib/chat/catalog";+import type { ChatMe, ChatThreadView } from "@/lib/chat/types";+import { toastError } from "@/lib/refusals";+import { cn } from "@/lib/utils";+import { CharacterFace } from "./character-face";+import { chatSend } from "./hooks";+import { ReplyBody } from "./prose";++/** Mango Chilli's mark: its two colours, used only for this mode. */+export const CHILLI_BG = "bg-[linear-gradient(135deg,#ffb020_0%,#ff6a2b_55%,#e8352b_100%)]";++export function ChilliDot({ className }: { className?: string }) {+ return <span className={cn("inline-block size-2.5 rounded-full", CHILLI_BG, className)} aria-hidden />;+}++// ---------------------------------------------------------------------------++/** Turn Mango Chilli mode on, after the person says they're 18 or older. */+export function MangoChilliDialog({ open, onOpenChange, onDone }: { open: boolean; onOpenChange: (o: boolean) => void; onDone?: () => void }) {+ const qc = useQueryClient();+ const [adult, setAdult] = useState(false);+ const [saving, setSaving] = useState(false);+ const turnOn = async () => {+ setSaving(true);+ try {+ const me = await chatSend<ChatMe>("/api/chat/me", "PATCH", { mature: true, adult: true });+ qc.setQueryData(["chat", "me"], me);+ void qc.invalidateQueries({ queryKey: ["chat"] });+ onOpenChange(false);+ onDone?.();+ } catch (e) {+ toastError(e);+ } finally {+ setSaving(false);+ }+ };+ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="overflow-hidden p-0 sm:max-w-[420px]">+ <div className={cn("relative h-28", CHILLI_BG)}>+ <span className="absolute bottom-3 left-5 font-heading text-[34px] leading-none text-white drop-shadow-sm">Mango Chilli</span>+ </div>+ <div className="space-y-4 px-5 pb-5">+ <DialogHeader className="space-y-1.5 text-left">+ <DialogTitle className="text-[17px]">Turn on {MANGO_CHILLI.name}?</DialogTitle>+ <DialogDescription className="text-[14px] leading-relaxed">{MANGO_CHILLI.blurb} Every character stays a fictional adult. You can turn it off any time.</DialogDescription>+ </DialogHeader>+ <label className="flex cursor-pointer items-start gap-3 rounded-xl border p-3 text-[14px] leading-snug has-[:checked]:border-[#ff6a2b]">+ <input type="checkbox" checked={adult} onChange={(e) => setAdult(e.target.checked)} className="mt-0.5 size-4 accent-[#ff6a2b]" />+ {MANGO_CHILLI.confirm}+ </label>+ <DialogFooter className="gap-2 sm:justify-end">+ <Button variant="ghost" onClick={() => onOpenChange(false)}>+ Not now+ </Button>+ <Button disabled={!adult || saving} onClick={() => void turnOn()} className={cn("text-white hover:opacity-90", CHILLI_BG)}>+ {saving && <Loader2 className="animate-spin" />}+ Turn on+ </Button>+ </DialogFooter>+ </div>+ </DialogContent>+ </Dialog>+ );+}++// ---------------------------------------------------------------------------++/** Suggestions from OpenRouter's list (src/lib/catalog/llm-providers.ts); any model id works. */+const KEY_MODELS = [+ { id: "google/gemma-4-31b-it:free", label: "Gemma 4 31B (free)" },+ { id: "openrouter/free", label: "Any free model" },+ { id: "deepseek/deepseek-v4.1-flash-1017", label: "DeepSeek V4.1 Flash" },+ { id: "x-ai/grok-4.7", label: "Grok 4.7" },+ { id: "anthropic/claude-opus-5.5", label: "Claude Opus 5.5" },+];++/** Chat settings: Mango Chilli mode, and which model answers (Fuobe's free one, or the person's own OpenRouter key). */+export function ChatSettingsDialog({ open, onOpenChange, me }: { open: boolean; onOpenChange: (o: boolean) => void; me: ChatMe | undefined }) {+ const qc = useQueryClient();+ const [chilli, setChilli] = useState(false);+ const [key, setKey] = useState("");+ const [busy, setBusy] = useState<string | null>(null);+ const update = (m: ChatMe) => {+ qc.setQueryData(["chat", "me"], m);+ void qc.invalidateQueries({ queryKey: ["chat"] });+ };+ const patch = async (body: Record<string, unknown>, what: string) => {+ setBusy(what);+ try {+ update(await chatSend<ChatMe>("/api/chat/me", "PATCH", body));+ } catch (e) {+ toastError(e);+ } finally {+ setBusy(null);+ }+ };+ const saveKey = async () => {+ setBusy("key");+ try {+ await chatSend("/api/chat/key", "PUT", { key: key.trim() });+ setKey("");+ update(await chatSend<ChatMe>("/api/chat/me", "GET"));+ toast.success("Key saved. Replies now come from your OpenRouter account.");+ } catch (e) {+ toastError(e);+ } finally {+ setBusy(null);+ }+ };+ const removeKey = async () => {+ setBusy("remove");+ try {+ await chatSend("/api/chat/key", "DELETE");+ update(await chatSend<ChatMe>("/api/chat/me", "GET"));+ } catch (e) {+ toastError(e);+ } finally {+ setBusy(null);+ }+ };+ const engine = me?.engine ?? "site";+ return (+ <>+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="max-h-[90svh] overflow-y-auto sm:max-w-[480px]">+ <DialogHeader>+ <DialogTitle>Chat settings</DialogTitle>+ </DialogHeader>++ <section className="space-y-3">+ <h3 className="text-[13px] font-medium text-muted-foreground">Who answers</h3>+ <TabRow role="radiogroup" aria-label="Who answers" fade={false} className="w-fit">+ <button role="radio" aria-checked={engine === "site"} className={TAB_PILL} {...onAttr(engine === "site")} onClick={() => engine !== "site" && void patch({ engine: "site" }, "engine")}>+ Fuobe's free model+ </button>+ <button+ role="radio"+ aria-checked={engine === "key"}+ className={TAB_PILL}+ {...onAttr(engine === "key")}+ disabled={!me?.key}+ onClick={() => engine !== "key" && void patch({ engine: "key" }, "engine")}+ title={me?.key ? undefined : "Add your OpenRouter key below first"}+ >+ Your OpenRouter key+ </button>+ </TabRow>+ <p className="text-[13px] leading-relaxed text-muted-foreground">+ {engine === "site"+ ? "Free, on Fuobe's own GPUs. It can be busy at peak times."+ : "Replies come from your OpenRouter account, with the model you pick. OpenRouter bills you for paid models."}+ </p>+ {me?.key ? (+ <div className="space-y-2 rounded-xl border p-3">+ <div className="flex items-center gap-2 text-[14px]">+ <KeyRound className="size-4 text-muted-foreground" />+ <span className="flex-1">Key ending in {me.key.last4}</span>+ <Button variant="ghost" size="sm" onClick={() => void removeKey()} disabled={busy === "remove"}>+ {busy === "remove" ? <Loader2 className="animate-spin" /> : <Trash2 />}+ Remove+ </Button>+ </div>+ <label className="block space-y-1.5">+ <span className="text-[12px] font-medium text-muted-foreground">Model</span>+ <div className="flex flex-wrap gap-1.5">+ {KEY_MODELS.map((m) => (+ <button+ key={m.id}+ type="button"+ onClick={() => void patch({ model: m.id }, "model")}+ className={cn("rounded-full border px-2.5 py-1 text-[12.5px]", me.key?.model === m.id ? "border-primary bg-brand-faint text-brand-text" : "hover:bg-accent")}+ >+ {m.label}+ </button>+ ))}+ </div>+ <Input+ defaultValue={me.key.model}+ placeholder="Any OpenRouter model id"+ onBlur={(e) => e.target.value.trim() && e.target.value.trim() !== me.key?.model && void patch({ model: e.target.value.trim() }, "model")}+ className="mt-1.5"+ />+ </label>+ </div>+ ) : (+ <div className="space-y-2 rounded-xl border p-3">+ <p className="text-[13px] leading-relaxed text-muted-foreground">+ Use your own key for stronger models or when the free one is busy. Get one at{" "}+ <a href="https://openrouter.ai/settings/keys" target="_blank" rel="noopener noreferrer" className="text-brand-text underline underline-offset-2">+ openrouter.ai+ </a>+ . It's stored encrypted and never shown again.+ </p>+ <div className="flex gap-2">+ <Input type="password" autoComplete="off" value={key} onChange={(e) => setKey(e.target.value)} placeholder="sk-or-…" aria-label="OpenRouter key" />+ <Button onClick={() => void saveKey()} disabled={!key.trim() || busy === "key"}>+ {busy === "key" && <Loader2 className="animate-spin" />}+ Save+ </Button>+ </div>+ </div>+ )}+ </section>++ <section className="space-y-2 border-t pt-4">+ <div className="flex items-center gap-3">+ <ChilliDot />+ <div className="min-w-0 flex-1">+ <p className="text-[14px] font-medium">{MANGO_CHILLI.name}</p>+ <p className="text-[13px] leading-snug text-muted-foreground">{MANGO_CHILLI.blurb}</p>+ </div>+ <Switch+ checked={!!me?.mature}+ disabled={busy === "mature"}+ onCheckedChange={(on) => (on ? setChilli(true) : void patch({ mature: false }, "mature"))}+ aria-label={MANGO_CHILLI.name}+ />+ </div>+ </section>+ </DialogContent>+ </Dialog>+ <MangoChilliDialog open={chilli} onOpenChange={setChilli} />+ </>+ );+}++// ---------------------------------------------------------------------------++/** A writing tool's short form; its answers become the chat's first message. */+export function WriteToolDialog({ tool, onOpenChange, onStart }: { tool: WriteTool | null; onOpenChange: (o: boolean) => void; onStart: (values: Record<string, string>, tone: string | null) => Promise<void> }) {+ const [values, setValues] = useState<Record<string, string>>({});+ const [tone, setTone] = useState<string | null>(null);+ const [busy, setBusy] = useState(false);+ const ready = !!tool && tool.fields.every((f) => f.optional || values[f.id]?.trim());+ return (+ <Dialog+ open={!!tool}+ onOpenChange={(o) => {+ if (!o) {+ setValues({});+ setTone(null);+ }+ onOpenChange(o);+ }}+ >+ <DialogContent className="sm:max-w-[480px]">+ {tool && (+ <>+ <DialogHeader>+ <DialogTitle>{tool.name}</DialogTitle>+ <DialogDescription>{tool.blurb}</DialogDescription>+ </DialogHeader>+ <form+ className="space-y-3.5"+ onSubmit={async (e) => {+ e.preventDefault();+ if (!ready) return;+ setBusy(true);+ try {+ await onStart(values, tone);+ } finally {+ setBusy(false);+ }+ }}+ >+ {tool.fields.map((f, i) => (+ <label key={f.id} className="block space-y-1.5">+ <span className="text-[13px] font-medium">+ {f.label}+ {f.optional && <span className="font-normal text-muted-foreground"> (optional)</span>}+ </span>+ {f.long ? (+ <Textarea+ autoFocus={i === 0}+ value={values[f.id] ?? ""}+ onChange={(e) => setValues({ ...values, [f.id]: e.target.value })}+ placeholder={f.placeholder}+ rows={3}+ maxLength={2000}+ />+ ) : (+ <Input autoFocus={i === 0} value={values[f.id] ?? ""} onChange={(e) => setValues({ ...values, [f.id]: e.target.value })} placeholder={f.placeholder} maxLength={200} />+ )}+ </label>+ ))}+ {tool.tones && (+ <div className="space-y-1.5">+ <span className="text-[13px] font-medium">Tone</span>+ <div className="flex flex-wrap gap-1.5">+ {tool.tones.map((t) => (+ <button+ key={t}+ type="button"+ onClick={() => setTone(tone === t ? null : t)}+ aria-pressed={tone === t}+ className={cn("rounded-full border px-3 py-1 text-[13px]", tone === t ? "border-primary bg-brand-faint text-brand-text" : "hover:bg-accent")}+ >+ {t}+ </button>+ ))}+ </div>+ </div>+ )}+ <DialogFooter>+ <Button type="submit" disabled={!ready || busy}>+ {busy && <Loader2 className="animate-spin" />}+ Write it+ </Button>+ </DialogFooter>+ </form>+ </>+ )}+ </DialogContent>+ </Dialog>+ );+}++// ---------------------------------------------------------------------------++/** A Play format that needs words or a picture first. */+export function PlayDialog({ play, onOpenChange, onStart }: { play: PlayFormat | null; onOpenChange: (o: boolean) => void; onStart: (input: string, image: string | null) => Promise<void> }) {+ const [input, setInput] = useState("");+ const [image, setImage] = useState<{ preview: string; url?: string } | null>(null);+ const [busy, setBusy] = useState(false);+ const file = useRef<HTMLInputElement>(null);+ const add = async (f: File | undefined) => {+ if (!f) return;+ const preview = URL.createObjectURL(f);+ setImage({ preview });+ try {+ const a = await uploadFile(f);+ setImage({ preview, url: a.url });+ } catch (e) {+ setImage(null);+ toastError(e, "That picture couldn't be added.");+ }+ };+ const ready = !!play && (play.picture ? !!image?.url : !play.ask || input.trim().length > 0);+ return (+ <Dialog+ open={!!play}+ onOpenChange={(o) => {+ if (!o) {+ setInput("");+ setImage(null);+ }+ onOpenChange(o);+ }}+ >+ <DialogContent className="sm:max-w-[440px]">+ {play && (+ <form+ className="space-y-4"+ onSubmit={async (e) => {+ e.preventDefault();+ if (!ready) return;+ setBusy(true);+ try {+ await onStart(input, image?.url ?? null);+ } finally {+ setBusy(false);+ }+ }}+ >+ <DialogHeader>+ <DialogTitle className="flex items-center gap-2">+ <span aria-hidden>{play.emoji}</span>+ {play.name}+ </DialogTitle>+ <DialogDescription>{play.blurb}</DialogDescription>+ </DialogHeader>+ {play.picture && (+ <>+ <input ref={file} type="file" accept="image/png,image/jpeg,image/webp" className="hidden" onChange={(e) => void add(e.target.files?.[0])} />+ <button+ type="button"+ onClick={() => file.current?.click()}+ className="relative grid aspect-[4/5] w-full place-items-center overflow-hidden rounded-2xl border border-dashed bg-muted/40 text-muted-foreground hover:bg-muted"+ >+ {image ? (+ <>+ {/* eslint-disable-next-line @next/next/no-img-element */}+ <img src={image.preview} alt="" className="absolute inset-0 size-full object-cover" />+ {!image.url && <Loader2 className="relative size-6 animate-spin text-white drop-shadow" />}+ </>+ ) : (+ <span className="flex flex-col items-center gap-2 text-[14px]">+ <ImagePlus className="size-6" />+ Add a full-length photo of your outfit+ </span>+ )}+ </button>+ </>+ )}+ {play.ask && (+ <label className="block space-y-1.5">+ <span className="text-[13px] font-medium">{play.ask.label}</span>+ <Input autoFocus value={input} onChange={(e) => setInput(e.target.value)} placeholder={play.ask.placeholder} maxLength={600} />+ </label>+ )}+ <DialogFooter>+ <Button type="submit" disabled={!ready || busy}>+ {busy && <Loader2 className="animate-spin" />}+ Play+ </Button>+ </DialogFooter>+ </form>+ )}+ </DialogContent>+ </Dialog>+ );+}++// ---------------------------------------------------------------------------++/** Share a chat: a preview of what goes public, then its link, its picture card and Stop sharing. */+export function ShareDialog({ thread, open, onOpenChange }: { thread: ChatThreadView; open: boolean; onOpenChange: (o: boolean) => void }) {+ const qc = useQueryClient();+ const [busy, setBusy] = useState<string | null>(null);+ const [copied, setCopied] = useState(false);+ const token = thread.shareToken;+ const url = token && typeof window !== "undefined" ? `${window.location.origin}/c/${token}` : null;+ const shown = thread.messages.filter((m) => m.content.trim()).slice(-12);+ const c = thread.characterCard;+ const refresh = () => qc.invalidateQueries({ queryKey: ["chat", "thread", thread.id] });++ const create = async () => {+ setBusy("create");+ try {+ const r = await chatSend<{ token: string }>(`/api/chat/threads/${thread.id}/share`, "POST", {});+ qc.setQueryData<ChatThreadView>(["chat", "thread", thread.id], (t) => (t ? { ...t, shareToken: r.token } : t));+ const link = `${window.location.origin}/c/${r.token}`;+ await navigator.clipboard?.writeText(link).catch(() => {});+ setCopied(true);+ setTimeout(() => setCopied(false), 1800);+ toast.success("Link copied. Anyone with it can read this chat.");+ } catch (e) {+ toastError(e);+ } finally {+ setBusy(null);+ }+ };+ const stop = async () => {+ setBusy("stop");+ try {+ await chatSend(`/api/chat/threads/${thread.id}/share`, "DELETE");+ qc.setQueryData<ChatThreadView>(["chat", "thread", thread.id], (t) => (t ? { ...t, shareToken: null } : t));+ void refresh();+ toast.success("Stopped sharing. The link no longer works.");+ } catch (e) {+ toastError(e);+ } finally {+ setBusy(null);+ }+ };+ const copy = async () => {+ if (!url) return;+ await navigator.clipboard?.writeText(url).catch(() => {});+ setCopied(true);+ setTimeout(() => setCopied(false), 1800);+ };+ const native = async () => {+ if (!url) return;+ if (navigator.share) await navigator.share({ title: thread.title, url }).catch(() => {});+ else await copy();+ };++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="max-h-[92svh] overflow-y-auto sm:max-w-[520px]">+ <DialogHeader>+ <DialogTitle>Share this chat</DialogTitle>+ <DialogDescription>+ {token ? "Anyone with the link can read the part below. New messages aren't added: share again to update it." : "Makes a public link to the last messages below. Pictures you sent stay private."}+ </DialogDescription>+ </DialogHeader>+ <div className="max-h-[42svh] space-y-3 overflow-y-auto rounded-2xl border bg-muted/30 p-4">+ {c && (+ <div className="flex items-center gap-2.5 pb-1">+ <CharacterFace name={c.name} accent={c.accent} portrait={c.portrait} className="size-8" />+ <span className="font-heading text-[19px] leading-none">{c.name}</span>+ </div>+ )}+ {shown.map((m) =>+ m.role === "user" ? (+ <p key={m.id} className="ml-auto w-fit max-w-[85%] rounded-2xl rounded-br-md bg-foreground px-3 py-2 text-[14px] text-background">+ {m.content || "(a picture)"}+ </p>+ ) : (+ <div key={m.id} className="text-[14px]">+ <ReplyBody text={m.content} compact />+ </div>+ ),+ )}+ </div>+ {token ? (+ <div className="space-y-3">+ <div className="flex items-center gap-2 rounded-xl border bg-background p-1.5 pl-3">+ <span className="min-w-0 flex-1 truncate text-[13.5px] text-muted-foreground">{url}</span>+ <Button size="sm" onClick={() => void copy()}>+ {copied ? <Check /> : <Copy />}+ {copied ? "Copied" : "Copy"}+ </Button>+ </div>+ <div className="flex flex-wrap gap-2">+ <Button variant="secondary" size="sm" onClick={() => void native()}>+ <Link2 />+ Share…+ </Button>+ <Button variant="secondary" size="sm" asChild>+ <a href={`/c/${token}/opengraph-image`} download={`${thread.title.slice(0, 40) || "chat"}.png`}>+ <Download />+ Picture card+ </a>+ </Button>+ <Button variant="secondary" size="sm" onClick={() => void create()} disabled={!!busy}>+ {busy === "create" && <Loader2 className="animate-spin" />}+ Update+ </Button>+ <Button variant="ghost" size="sm" onClick={() => void stop()} disabled={!!busy} className="ml-auto text-muted-foreground">+ {busy === "stop" ? <Loader2 className="animate-spin" /> : <Link2Off />}+ Stop sharing+ </Button>+ </div>+ </div>+ ) : (+ <DialogFooter>+ <Button onClick={() => void create()} disabled={!!busy}>+ {busy === "create" ? <Loader2 className="animate-spin" /> : <Link2 />}+ Create link+ </Button>+ </DialogFooter>+ )}+ </DialogContent>+ </Dialog>+ );+}diff --git a/src/components/chat/hooks.ts b/src/components/chat/hooks.tsnew file mode 100644index 00000000..717d660d--- /dev/null+++ b/src/components/chat/hooks.ts@@ -0,0 +1,175 @@+"use client";++import { useQuery, useQueryClient } from "@tanstack/react-query";+import { useCallback, useRef, useState } from "react";+import type { CharacterCard, ChatKind } from "@/lib/chat/catalog";+import type { ChatEvent, ChatMe, ChatMessage, ChatThreadSummary, ChatThreadView } from "@/lib/chat/types";+import { responseError } from "@/lib/refusals";++async function json<T>(res: Response): Promise<T> {+ const body = (await res.json().catch(() => ({}))) as T & { error?: string; code?: string };+ if (!res.ok) throw responseError(res, Object.assign(new Error(body.error ?? "Something went wrong. Try again."), { status: res.status }, body.code && { code: body.code }));+ return body;+}++export const chatSend = async <T,>(url: string, method: string, body?: unknown) =>+ json<T>(await fetch(url, { method, headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) }));++export function useChatMe(enabled = true) {+ return useQuery({ queryKey: ["chat", "me"], queryFn: async () => json<ChatMe>(await fetch("/api/chat/me")), staleTime: 15_000, enabled });+}++export function useChatThreads(enabled = true, q = "") {+ return useQuery({+ queryKey: ["chat", "threads", q.trim()],+ queryFn: async () => json<{ items: ChatThreadSummary[] }>(await fetch(`/api/chat/threads${q.trim() ? `?q=${encodeURIComponent(q.trim())}` : ""}`)),+ staleTime: 5_000,+ enabled,+ });+}++export function useCharacters(enabled = true) {+ return useQuery({ queryKey: ["chat", "characters"], queryFn: async () => json<{ items: CharacterCard[] }>(await fetch("/api/chat/characters")), staleTime: 30_000, enabled });+}++export function useChatThread(id: string, enabled = true) {+ return useQuery({ queryKey: ["chat", "thread", id], queryFn: async () => json<ChatThreadView>(await fetch(`/api/chat/threads/${id}`)), staleTime: 0, enabled, retry: false });+}++export interface StartChat {+ kind: ChatKind;+ characterId?: string | null;+ tool?: string | null;+ play?: string | null;+ text?: string | null;+ image?: string | null;+}++/** Start a chat; the thread page asks for the first reply. */+export function useStartChat() {+ const qc = useQueryClient();+ return useCallback(+ async (s: StartChat) => {+ const t = await chatSend<ChatThreadView>("/api/chat/threads", "POST", s);+ qc.setQueryData(["chat", "thread", t.id], t);+ void qc.invalidateQueries({ queryKey: ["chat", "threads"] });+ return t;+ },+ [qc],+ );+}++export type ReplyState =+ | { phase: "idle" }+ | { phase: "waiting" }+ | { phase: "writing"; text: string }+ | { phase: "failed"; message: string; code: string; retryAfterS?: number };++/**+ * Ask for a reply and follow its stream. The thread's cached view gets the person's message and the saved reply as+ * they arrive; `state` shows what's happening in between.+ */+export function useReply(threadId: string) {+ const qc = useQueryClient();+ const [state, setState] = useState<ReplyState>({ phase: "idle" });+ /** The reply that arrived in one piece (no text on the way): the page shows it as if written. */+ const [revealId, setRevealId] = useState<string | null>(null);+ const ctl = useRef<AbortController | null>(null);++ const patch = useCallback(+ (fn: (t: ChatThreadView) => ChatThreadView) => qc.setQueryData<ChatThreadView>(["chat", "thread", threadId], (t) => (t ? fn(t) : t)),+ [qc, threadId],+ );++ const ask = useCallback(+ async (body: { text?: string; image?: string | null; retry?: boolean; edit?: string }) => {+ ctl.current?.abort();+ const ac = new AbortController();+ ctl.current = ac;+ setState({ phase: "waiting" });+ // Shown at once; the server's copy replaces it.+ const temp: ChatMessage | null = body.text || body.image ? { id: `tmp_${Date.now()}`, role: "user", content: body.text ?? "", image: body.image ?? null, createdAt: Date.now() } : null;+ patch((t) => {+ let messages = t.messages;+ if (body.edit) {+ const i = messages.findIndex((m) => m.id === body.edit);+ if (i >= 0) messages = messages.slice(0, i);+ } else if (body.retry && messages.at(-1)?.role === "assistant" && messages.length > 1) messages = messages.slice(0, -1);+ return { ...t, messages: temp ? [...messages, temp] : messages };+ });+ let res: Response;+ try {+ res = await fetch(`/api/chat/threads/${threadId}/reply`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(body),+ signal: ac.signal,+ });+ } catch {+ if (ac.signal.aborted) return setState({ phase: "idle" });+ return setState({ phase: "failed", code: "failed", message: "Couldn't reach Fuobe. Check your connection and try again." });+ }+ if (!res.ok || !res.body) {+ const e = (await res.json().catch(() => ({}))) as { error?: string; code?: string };+ // The guest card opens by itself (watchGuestRefusals); the message stays for Try again.+ responseError(res, new Error(e.error ?? ""));+ void qc.invalidateQueries({ queryKey: ["chat", "thread", threadId] });+ return setState({ phase: "failed", code: e.code ?? "failed", message: e.error ?? "The reply didn't start. Try again." });+ }+ const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();+ let buf = "";+ let ended = false;+ let streamed = false;+ let texts = 0;+ try {+ for (;;) {+ const { value, done } = await reader.read();+ if (done) break;+ buf += value;+ let nl: number;+ while ((nl = buf.indexOf("\n")) >= 0) {+ const line = buf.slice(0, nl).trim();+ buf = buf.slice(nl + 1);+ if (!line) continue;+ let e: ChatEvent;+ try {+ e = JSON.parse(line) as ChatEvent;+ } catch {+ continue;+ }+ if (e.type === "user") patch((t) => ({ ...t, messages: [...t.messages.filter((m) => m.id !== temp?.id), e.message] }));+ else if (e.type === "text") {+ // Only a model that streams sends text on the way; a whole reply comes with done alone.+ texts++;+ streamed = texts > 0;+ setState({ phase: "writing", text: e.text });+ } else if (e.type === "done") {+ ended = true;+ if (!streamed) setRevealId(e.message.id);+ patch((t) => ({ ...t, title: e.title, messages: [...t.messages, e.message] }));+ setState({ phase: "idle" });+ void qc.invalidateQueries({ queryKey: ["chat", "threads"] });+ } else if (e.type === "error") {+ ended = true;+ setState({ phase: "failed", code: e.code, message: e.message, retryAfterS: e.retryAfterS });+ }+ }+ }+ } catch {+ if (ac.signal.aborted) {+ ended = true;+ setState({ phase: "idle" });+ }+ }+ if (!ended) setState({ phase: "failed", code: "failed", message: "The reply was cut off. Try again." });+ },+ [patch, qc, threadId],+ );++ const stop = useCallback(() => {+ ctl.current?.abort();+ setState({ phase: "idle" });+ }, []);++ return { state, ask, stop, revealId };+}diff --git a/src/components/chat/prose.tsx b/src/components/chat/prose.tsxnew file mode 100644index 00000000..4731ecb6--- /dev/null+++ b/src/components/chat/prose.tsx@@ -0,0 +1,79 @@+import { Clapperboard, ImageIcon, Music4 } from "lucide-react";+import Link from "next/link";+import ReactMarkdown, { type Components } from "react-markdown";+import remarkGfm from "remark-gfm";+import { makeItHref, splitMakeIts, type MakeIt } from "@/lib/chat/prompt";+import { cn } from "@/lib/utils";++const STUDIO = {+ image: { label: "Make it in Image", icon: ImageIcon },+ video: { label: "Make it in Video", icon: Clapperboard },+ music: { label: "Make it in Music", icon: Music4 },+} as const;++/** Markdown as chat replies use it: no raw HTML, links open in a new tab, *actions* read as stage directions. */+const COMPONENTS: Components = {+ p: ({ children }) => <p className="break-words">{children}</p>,+ em: ({ children }) => <em className="text-muted-foreground italic">{children}</em>,+ strong: ({ children }) => <strong className="font-semibold text-foreground">{children}</strong>,+ ul: ({ children }) => <ul className="list-disc space-y-1 pl-5 marker:text-muted-foreground">{children}</ul>,+ ol: ({ children }) => <ol className="list-decimal space-y-1 pl-5 marker:text-muted-foreground">{children}</ol>,+ h1: ({ children }) => <h3 className="font-heading pt-1 text-[22px] leading-snug">{children}</h3>,+ h2: ({ children }) => <h3 className="font-heading pt-1 text-[22px] leading-snug">{children}</h3>,+ h3: ({ children }) => <h3 className="font-heading pt-1 text-[21px] leading-snug">{children}</h3>,+ h4: ({ children }) => <h4 className="pt-1 font-semibold">{children}</h4>,+ a: ({ href, children }) => (+ <a href={href} target="_blank" rel="noopener noreferrer nofollow" className="text-brand-text underline underline-offset-2">+ {children}+ </a>+ ),+ code: ({ children }) => <code className="rounded bg-muted px-1 py-0.5 font-mono text-[0.9em]">{children}</code>,+ pre: ({ children }) => <pre className="overflow-x-auto rounded-xl bg-muted p-3 text-[13px]">{children}</pre>,+ blockquote: ({ children }) => <blockquote className="border-l-2 border-border-strong pl-3 text-muted-foreground">{children}</blockquote>,+ hr: () => <hr className="border-border" />,+ table: ({ children }) => (+ <div className="overflow-x-auto">+ <table className="w-full text-[14px]">{children}</table>+ </div>+ ),+ th: ({ children }) => <th className="border-b px-2 py-1 text-left font-medium">{children}</th>,+ td: ({ children }) => <td className="border-b px-2 py-1 align-top">{children}</td>,+};++export function Markdown({ text, className }: { text: string; className?: string }) {+ return (+ <div className={cn("space-y-3 text-[15.5px] leading-relaxed", className)}>+ <ReactMarkdown remarkPlugins={[remarkGfm]} components={COMPONENTS} skipHtml>+ {text}+ </ReactMarkdown>+ </div>+ );+}++/** A prompt the reply suggested, with the button that opens its studio filled in. */+export function MakeItCard({ make, compact }: { make: MakeIt; compact?: boolean }) {+ const s = STUDIO[make.studio];+ const Icon = s.icon;+ return (+ <div className={cn("group rounded-2xl border bg-background/80 p-3", compact && "p-2.5")}>+ <p className="line-clamp-3 text-[13.5px] leading-snug text-muted-foreground">{make.prompt}</p>+ <Link+ href={makeItHref(make)}+ className="mt-2.5 inline-flex h-8 items-center gap-1.5 rounded-full bg-foreground px-3.5 text-[13px] font-medium text-background transition-opacity hover:opacity-90 focus-visible:ring-4 focus-visible:ring-brand-faint focus-visible:outline-none"+ >+ <Icon className="size-3.5" />+ {s.label}+ </Link>+ </div>+ );+}++/** A reply: its words, with each suggested prompt as a Make it card where it appears. */+export function ReplyBody({ text, compact }: { text: string; compact?: boolean }) {+ const parts = splitMakeIts(text);+ return (+ <div className="space-y-3">+ {parts.map((p, i) => (p.kind === "text" ? <Markdown key={i} text={p.text} /> : <MakeItCard key={i} make={p.make} compact={compact} />))}+ </div>+ );+}diff --git a/src/components/chat/share-page.tsx b/src/components/chat/share-page.tsxnew file mode 100644index 00000000..c1192c07--- /dev/null+++ b/src/components/chat/share-page.tsx@@ -0,0 +1,119 @@+"use client";++import Link from "next/link";+import { useState, useSyncExternalStore } from "react";+import { Button } from "@/components/ui/button";+import { MANGO_CHILLI } from "@/lib/chat/catalog";+import { ADULT_OK_KEY } from "@/lib/chat/share";+import type { ChatShareSnapshot } from "@/lib/chat/types";+import { cn } from "@/lib/utils";+import { CharacterFace } from "./character-face";+import { CHILLI_BG } from "./dialogs";+import { Markdown, ReplyBody } from "./prose";++/**+ * A shared chat's public page (/c/<token>): the character (or the game or tool), the shared lines, and a way in for the+ * visitor: chat with the same character, or start their own. A Mango Chilli chat asks the visitor's age first.+ */+const readAdult = (): boolean => {+ try {+ return window.localStorage.getItem(ADULT_OK_KEY) === "1";+ } catch {+ return false;+ }+};+const onStorage = (cb: () => void) => {+ window.addEventListener("storage", cb);+ return () => window.removeEventListener("storage", cb);+};++export function ChatSharePage({ token, snap, portrait }: { token: string; snap: ChatShareSnapshot; portrait: boolean }) {+ // Null on the server (it can't know): the gate waits for the browser.+ const remembered = useSyncExternalStore<boolean | null>(onStorage, readAdult, () => null);+ const [said, setSaid] = useState(false);+ const adultOk = !snap.mature || said ? true : remembered;+ const setAdultOk = (v: boolean) => setSaid(v);++ const c = snap.character;+ const accent = c?.accent ?? (["#1d1640", "#6a5ee7"] as [string, string]);+ const cta = c ? `Chat with ${c.name}` : snap.kind === "play" ? "Play it yourself" : "Start your own chat";+ const ctaHref = c ? `/chat?from=${token}` : snap.kind === "play" || snap.kind === "write" ? "/chat?kind=" + snap.kind : "/chat";++ return (+ <div className="flex min-h-svh flex-col bg-background">+ <header className="mx-auto flex w-full max-w-[760px] items-center justify-between gap-3 px-4 pt-5 sm:px-6">+ <Link href="/" className="font-heading text-[22px] leading-none">+ Fuobe+ </Link>+ <Button asChild size="sm" className={cn("rounded-full", snap.mature && "text-white " + CHILLI_BG)}>+ <Link href={ctaHref}>{cta}</Link>+ </Button>+ </header>+ <main className="mx-auto w-full max-w-[760px] min-w-0 flex-1 px-4 pt-8 pb-20 sm:px-6 sm:pt-12">+ <div className="flex items-center gap-4">+ {c ? (+ <CharacterFace name={c.name} accent={accent} src={portrait ? `/c/${token}/portrait` : null} rounded="card" className="aspect-[3/4] w-24 shrink-0 shadow-strong sm:w-28" />+ ) : null}+ <div className="min-w-0">+ <p className="text-[13px] text-muted-foreground">{snap.mature ? `${MANGO_CHILLI.short} · 18+` : snap.label ? snap.label : "A chat on Fuobe"}</p>+ <h1 className="mt-1 font-heading text-[clamp(32px,6vw,48px)] leading-[1.04] text-balance">{c?.name ?? snap.title}</h1>+ {c?.tagline && <p className="mt-1.5 text-[15px] text-muted-foreground">{c.tagline}</p>}+ </div>+ </div>++ {adultOk === null ? null : !adultOk ? (+ <div className="mt-10 overflow-hidden rounded-3xl border">+ <div className={cn("h-24", CHILLI_BG)} />+ <div className="space-y-3 p-5">+ <p className="text-[17px] font-medium">This chat is for adults</p>+ <p className="text-[14px] text-muted-foreground">It comes from {MANGO_CHILLI.name}, which can include mature themes and language.</p>+ <div className="flex flex-wrap gap-2 pt-1">+ <Button+ className={cn("text-white hover:opacity-90", CHILLI_BG)}+ onClick={() => {+ try {+ window.localStorage.setItem(ADULT_OK_KEY, "1");+ } catch {+ // Private mode: it asks again next time.+ }+ setAdultOk(true);+ }}+ >+ I'm 18 or older+ </Button>+ <Button variant="ghost" asChild>+ <Link href="/">Take me back</Link>+ </Button>+ </div>+ </div>+ </div>+ ) : (+ <ol className="mt-10 space-y-6">+ {snap.messages.map((m, i) => (+ <li key={i}>+ {m.role === "user" ? (+ <div className="ml-auto w-fit max-w-[85%] rounded-3xl rounded-br-lg bg-muted px-4 py-2.5 text-[15.5px] leading-relaxed">+ <Markdown text={m.content || "(a picture)"} className="space-y-2" />+ </div>+ ) : (+ <div>+ {c && <p className="mb-1 font-heading text-[17px] leading-none text-muted-foreground">{c.name}</p>}+ <ReplyBody text={m.content} />+ </div>+ )}+ </li>+ ))}+ </ol>+ )}++ <div className="mt-14 rounded-3xl border p-6 text-center">+ <p className="font-heading text-[28px] leading-tight">{c ? `Your turn with ${c.name}` : "Your turn"}</p>+ <p className="mx-auto mt-2 max-w-[46ch] text-[14.5px] text-muted-foreground">Free chat on Fuobe: ask anything, write, brainstorm ideas you can make in one tap, or step into a story.</p>+ <Button asChild className={cn("mt-5 rounded-full", snap.mature && "text-white " + CHILLI_BG)}>+ <Link href={ctaHref}>{cta}</Link>+ </Button>+ </div>+ </main>+ </div>+ );+}diff --git a/src/components/chat/thread-view.tsx b/src/components/chat/thread-view.tsxnew file mode 100644index 00000000..a7ba25dc--- /dev/null+++ b/src/components/chat/thread-view.tsx@@ -0,0 +1,459 @@+"use client";++import { useQueryClient } from "@tanstack/react-query";+import { ArrowLeft, Check, Copy, MoreHorizontal, Pencil, RotateCcw, Share2, Trash2, X } from "lucide-react";+import Link from "next/link";+import { useRouter } from "next/navigation";+import { useEffect, useLayoutEffect, useRef, useState } from "react";+import { PhoneNavButton } from "@/components/nav/phone-nav-button";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "@/components/ui/alert-dialog";+import { Button } from "@/components/ui/button";+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";+import { CHAT_KINDS, playFormat, writeTool, type CharacterCard } from "@/lib/chat/catalog";+import type { ChatMessage, ChatThreadView } from "@/lib/chat/types";+import { toastError } from "@/lib/refusals";+import { cn } from "@/lib/utils";+import { EngineLine, KindIcon, TypingDots, useReveal } from "./bits";+import { CharacterFace } from "./character-face";+import { ChatComposer, type ComposerHandle } from "./composer";+import { ChatSettingsDialog, ChilliDot, MangoChilliDialog, ShareDialog } from "./dialogs";+import { chatSend, useChatMe, useChatThread, useReply } from "./hooks";+import { Markdown, ReplyBody } from "./prose";++/** One chat: its messages, the reply as it's written, and the box to carry on. */+export function ThreadView({ id }: { id: string }) {+ const router = useRouter();+ const qc = useQueryClient();+ const view = useChatThread(id);+ const me = useChatMe();+ const { state, ask, stop, revealId: reveal } = useReply(id);+ const t = view.data;+ const [sharing, setSharing] = useState(false);+ const [settings, setSettings] = useState(false);+ const [chilli, setChilli] = useState(false);+ const [deleting, setDeleting] = useState(false);+ const [renaming, setRenaming] = useState(false);+ const [editing, setEditing] = useState<ChatMessage | null>(null);+ const composer = useRef<ComposerHandle>(null);+ const mature = !!me.data?.mature;+ const busy = state.phase === "waiting" || state.phase === "writing";++ // A new chat arrives with the person's first message: ask for its reply once.+ const asked = useRef(false);+ useEffect(() => {+ if (!t || asked.current) return;+ asked.current = true;+ if (t.messages.at(-1)?.role === "user") void ask({});+ }, [t, ask]);++ // Messages that arrive while the page is open animate in; the ones it opened with don't.+ const [openedAt] = useState(() => Date.now());++ // Follow the chat to its end, unless the person scrolled up to read: at once when it opens, smoothly after.+ const scroller = useRef<HTMLDivElement>(null);+ const pinned = useRef(true);+ const firstScroll = useRef(true);+ const streamed = state.phase === "writing" ? state.text.length : 0;+ useLayoutEffect(() => {+ const el = scroller.current;+ if (!el || !pinned.current || !t) return;+ const instant = firstScroll.current || window.matchMedia("(prefers-reduced-motion: reduce)").matches;+ firstScroll.current = false;+ el.scrollTo({ top: el.scrollHeight, behavior: instant ? "auto" : "smooth" });+ }, [t, t?.messages.length, streamed, state.phase]);++ const send = async (text: string, image: string | null) => {+ pinned.current = true;+ // A light tap on phones that have it, as the message goes.+ navigator.vibrate?.(8);+ if (editing) {+ const m = editing;+ setEditing(null);+ await ask({ text, edit: m.id, image });+ } else await ask({ text, image });+ };++ if (view.isError) {+ const code = (view.error as { code?: string }).code;+ return (+ <Frame>+ <div className="mx-auto max-w-md py-24 text-center">+ <p className="font-heading text-[26px]">{code === "mature-off" ? "This chat is in Mango Chilli mode" : "This chat isn't here any more"}</p>+ <p className="mt-2 text-[14px] text-muted-foreground">{code === "mature-off" ? "Turn the mode on to open it." : "It may have been deleted."}</p>+ <div className="mt-5 flex justify-center gap-2">+ {code === "mature-off" && <Button onClick={() => setChilli(true)}>Turn on Mango Chilli</Button>}+ <Button variant="outline" asChild>+ <Link href="/chat">Back to chats</Link>+ </Button>+ </div>+ </div>+ <MangoChilliDialog open={chilli} onOpenChange={setChilli} onDone={() => void view.refetch()} />+ </Frame>+ );+ }++ const c = t?.characterCard ?? null;+ const label = !t ? "" : c ? c.tagline : t.kind === "play" ? (playFormat(t.play)?.name ?? "Play") : t.kind === "write" ? (writeTool(t.tool)?.name ?? "Write") : CHAT_KINDS.find((k) => k.id === t.kind)?.label;+ const lastAssistant = t?.messages.findLast((m) => m.role === "assistant");+ const lastUser = t?.messages.findLast((m) => m.role === "user");+ const canRetry = !!t && !busy && t.messages.at(-1)?.role === "assistant" && t.messages.length > 1;++ return (+ <Frame>+ <header className="flex h-14 shrink-0 items-center gap-2 border-b px-3 sm:px-5">+ <Button variant="ghost" size="icon" asChild aria-label="All chats">+ <Link href="/chat">+ <ArrowLeft />+ </Link>+ </Button>+ {t && (c ? <CharacterFace name={c.name} accent={c.accent} portrait={c.portrait} className="size-8" /> : <span className="grid size-8 place-items-center rounded-full bg-muted text-muted-foreground"><KindIcon kind={t.kind} className="size-4" /></span>)}+ <div className="min-w-0 flex-1">+ {renaming && t ? (+ <form+ onSubmit={async (e) => {+ e.preventDefault();+ const v = new FormData(e.currentTarget).get("title");+ setRenaming(false);+ try {+ const r = await chatSend<ChatThreadView>(`/api/chat/threads/${id}`, "PATCH", { title: v });+ qc.setQueryData<ChatThreadView>(["chat", "thread", id], (x) => (x ? { ...x, title: r.title } : x));+ void qc.invalidateQueries({ queryKey: ["chat", "threads"] });+ } catch (err) {+ toastError(err);+ }+ }}+ >+ <input name="title" defaultValue={t.title} autoFocus onBlur={(e) => e.currentTarget.form?.requestSubmit()} maxLength={80} className="w-full rounded-md bg-muted px-2 py-1 text-[15px] font-medium outline-none" />+ </form>+ ) : (+ <>+ <p className="flex items-center gap-1.5 truncate text-[15px] leading-tight font-medium">+ {c ? c.name : t?.title}+ {t?.mature && <ChilliDot className="size-2" />}+ </p>+ {label && <p className="truncate text-[12px] leading-tight text-muted-foreground">{c ? label : t?.title !== label ? label : null}</p>}+ </>+ )}+ </div>+ {t && (+ <Button variant="ghost" size="sm" onClick={() => setSharing(true)}>+ <Share2 />+ <span className="hidden sm:inline">{t.shareToken ? "Shared" : "Share"}</span>+ </Button>+ )}+ {t && (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button variant="ghost" size="icon" aria-label="More">+ <MoreHorizontal />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuItem onSelect={() => setRenaming(true)}>+ <Pencil /> Rename+ </DropdownMenuItem>+ <DropdownMenuItem onSelect={() => setSettings(true)}>Chat settings</DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem variant="destructive" onSelect={() => setDeleting(true)}>+ <Trash2 /> Delete chat+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ )}+ <PhoneNavButton />+ </header>++ <div+ ref={scroller}+ className="min-h-0 flex-1 overflow-y-auto px-4 sm:px-6"+ onScroll={(e) => {+ const el = e.currentTarget;+ pinned.current = el.scrollHeight - el.scrollTop - el.clientHeight < 80;+ }}+ >+ <div className="mx-auto w-full max-w-[760px] py-6">+ {c && (+ <div className="mb-8 flex flex-col items-center text-center">+ <CharacterFace name={c.name} accent={c.accent} portrait={c.portrait} rounded="card" className="aspect-[3/4] w-32 shadow-strong sm:w-40" />+ <p className="mt-4 font-heading text-[30px] leading-none">{c.name}</p>+ <p className="mt-1.5 max-w-[46ch] text-[14px] text-muted-foreground">{c.tagline}</p>+ </div>+ )}+ {!t ? (+ <div className="space-y-4 pt-6">+ <div className="ml-auto h-10 w-2/3 animate-pulse rounded-3xl bg-muted" />+ <div className="h-24 w-full animate-pulse rounded-2xl bg-muted/60" />+ </div>+ ) : (+ <ol className="flex flex-col">+ {t.messages.map((m, i) => {+ const prev = t.messages[i - 1];+ const next = t.messages[i + 1];+ // A run: messages from the same side with no long pause between them sit close, and only the last+ // one has the tail (and the character's face).+ const gap = !prev || m.createdAt - prev.createdAt > 60 * 60_000;+ const first = gap || prev.role !== m.role;+ const tail = !next || next.role !== m.role || next.createdAt - m.createdAt > 60 * 60_000 || (m.role === "assistant" && busy && i === t.messages.length - 1);+ const fresh = m.createdAt > openedAt || m.id.startsWith("tmp_");+ return (+ <li key={m.id} className={cn(first ? "mt-5" : "mt-1", i === 0 && "mt-0")}>+ {gap && i > 0 && <p className="mb-3 text-center text-[11.5px] text-subtle-foreground">{stamp(m.createdAt)}</p>}+ {m.role === "user" ? (+ <UserTurn+ m={m}+ tail={tail}+ fresh={fresh}+ editable={!busy && m.id === lastUser?.id && !m.id.startsWith("tmp_")}+ onEdit={() => {+ setEditing(m);+ composer.current?.set(m.content);+ }}+ />+ ) : (+ <AssistantTurn+ m={m}+ character={c}+ first={first}+ tail={tail}+ fresh={fresh}+ reveal={m.id === reveal}+ last={m.id === lastAssistant?.id}+ canRetry={canRetry}+ onRetry={() => void ask({ retry: true })}+ />+ )}+ </li>+ );+ })}+ {busy && (+ <li aria-live="polite" className={cn(t.messages.at(-1)?.role === "assistant" ? "mt-1" : "mt-5")}>+ <Row character={c} tail>+ {state.phase === "writing" ? (+ <Bubble side="them" tail fresh>+ <ReplyBody text={state.text} />+ </Bubble>+ ) : (+ <Bubble side="them" tail fresh className="px-4 py-3.5">+ <TypingDots label={c ? `${c.name} is writing` : "Writing"} />+ </Bubble>+ )}+ </Row>+ </li>+ )}+ {state.phase === "failed" && (+ <li className="mt-5 animate-in duration-200 fade-in-0">+ <div className="flex flex-wrap items-center gap-3 rounded-2xl border bg-muted/40 p-3.5 text-[14px]">+ <p className="min-w-0 flex-1">{state.message}</p>+ {state.code === "key-refused" || state.code === "no-model" ? (+ <Button size="sm" variant="secondary" onClick={() => setSettings(true)}>+ Chat settings+ </Button>+ ) : state.code === "mature-off" ? (+ <Button size="sm" variant="secondary" onClick={() => setChilli(true)}>+ Turn on Mango Chilli+ </Button>+ ) : null}+ {t.messages.at(-1)?.role === "user" && (+ <Button size="sm" onClick={() => void ask({})}>+ <RotateCcw />+ Try again+ </Button>+ )}+ </div>+ </li>+ )}+ </ol>+ )}+ </div>+ </div>++ <div className="shrink-0 px-4 pb-[max(0.75rem,env(safe-area-inset-bottom))] sm:px-6">+ <div className="mx-auto w-full max-w-[760px]">+ {editing && (+ <div className="mb-1.5 flex items-center gap-2 px-2 text-[12.5px] text-muted-foreground">+ <Pencil className="size-3.5" />+ Changing your last message. Everything after it is written again.+ <button type="button" className="ml-auto inline-flex items-center gap-1 hover:text-foreground" onClick={() => setEditing(null)}>+ <X className="size-3.5" /> Cancel+ </button>+ </div>+ )}+ <ChatComposer+ ref={composer}+ mature={mature}+ busy={busy}+ onStop={stop}+ disabled={!t}+ placeholder={c ? `Reply to ${c.name.split(" ")[0]}…` : "Reply…"}+ onSend={send}+ footer={<EngineLine me={me.data} />}+ />+ <p className="mt-1.5 text-center text-[11.5px] text-subtle-foreground">{c ? "Write actions in *asterisks*. Characters are fictional, written by an AI." : "Replies are written by an AI and can be wrong."}</p>+ </div>+ </div>++ {t && <ShareDialog thread={t} open={sharing} onOpenChange={setSharing} />}+ <ChatSettingsDialog open={settings} onOpenChange={setSettings} me={me.data} />+ <MangoChilliDialog open={chilli} onOpenChange={setChilli} />+ <AlertDialog open={deleting} onOpenChange={setDeleting}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>Delete this chat?</AlertDialogTitle>+ <AlertDialogDescription>Its messages go for good{t?.shareToken ? ", and its share link stops working" : ""}.</AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>Keep it</AlertDialogCancel>+ <AlertDialogAction+ variant="destructive"+ onClick={async () => {+ try {+ await chatSend(`/api/chat/threads/${id}`, "DELETE");+ void qc.invalidateQueries({ queryKey: ["chat", "threads"] });+ router.push("/chat");+ } catch (e) {+ toastError(e);+ }+ }}+ >+ Delete+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </Frame>+ );+}++function Frame({ children }: { children: React.ReactNode }) {+ return <div className="flex h-content min-w-0 flex-col">{children}</div>;+}++/** "Today 14:02", "Yesterday 09:10" or "12 Nov 18:30": the label over a run after a long pause. */+function stamp(t: number): string {+ const d = new Date(t);+ const time = d.toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit" });+ const days = Math.round((new Date().setHours(0, 0, 0, 0) - new Date(t).setHours(0, 0, 0, 0)) / 86_400_000);+ return `${days === 0 ? "Today" : days === 1 ? "Yesterday" : d.toLocaleDateString(undefined, { day: "numeric", month: "short" })} ${time}`;+}++/** The spring a new bubble rises with (a little overshoot, settled in a third of a second). */+const SPRING = "animate-in fade-in-0 zoom-in-90 slide-in-from-bottom-3 duration-300 ease-[cubic-bezier(0.2,0.9,0.25,1.15)] motion-reduce:animate-none";++/** A message bubble: the person's on the right in the brand colour, the other side's on the left in grey. */+function Bubble({ side, tail, fresh, className, children }: { side: "me" | "them"; tail?: boolean; fresh?: boolean; className?: string; children: React.ReactNode }) {+ return (+ <div+ className={cn(+ "max-w-[min(85%,620px)] min-w-0 rounded-[22px] px-4 py-2.5 text-[15.5px] leading-relaxed break-words",+ side === "me" ? "origin-bottom-right bg-primary text-primary-foreground [&_a]:text-primary-foreground [&_em]:text-primary-foreground/80 [&_strong]:text-primary-foreground" : "origin-bottom-left bg-muted text-foreground",+ tail && (side === "me" ? "rounded-br-[6px]" : "rounded-bl-[6px]"),+ fresh && SPRING,+ className,+ )}+ >+ {children}+ </div>+ );+}++/** The other side's row: the character's face at the foot of a run, room for it on the rest. */+function Row({ character, tail, children }: { character: CharacterCard | null; tail?: boolean; children: React.ReactNode }) {+ return (+ <div className="flex items-end gap-2">+ {character && (tail ? <CharacterFace name={character.name} accent={character.accent} portrait={character.portrait} className="size-7" /> : <span className="w-7 shrink-0" aria-hidden />)}+ {children}+ </div>+ );+}++function UserTurn({ m, tail, fresh, editable, onEdit }: { m: ChatMessage; tail: boolean; fresh: boolean; editable: boolean; onEdit: () => void }) {+ return (+ <div className="group flex flex-col items-end gap-1">+ {m.image && (+ // eslint-disable-next-line @next/next/no-img-element+ <img src={m.image} alt="Your picture" className={cn("max-h-72 max-w-[70%] origin-bottom-right rounded-[22px] border object-cover", fresh && SPRING)} />+ )}+ {m.content && (+ <Bubble side="me" tail={tail} fresh={fresh}>+ <Markdown text={m.content} className="space-y-2" />+ </Bubble>+ )}+ {editable && (+ <button type="button" onClick={onEdit} className="inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[12px] text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100 hover:text-foreground focus-visible:opacity-100 max-sm:hidden">+ <Pencil className="size-3" /> Edit+ </button>+ )}+ </div>+ );+}++function AssistantTurn({+ m,+ character,+ first,+ tail,+ fresh,+ reveal,+ last,+ canRetry,+ onRetry,+}: {+ m: ChatMessage;+ character: CharacterCard | null;+ first: boolean;+ tail: boolean;+ fresh: boolean;+ reveal: boolean;+ last: boolean;+ canRetry: boolean;+ onRetry: () => void;+}) {+ const text = useReveal(m.content, reveal);+ const [copied, setCopied] = useState(false);+ const copy = (+ <button+ type="button"+ onClick={async () => {+ await navigator.clipboard?.writeText(m.content).catch(() => {});+ setCopied(true);+ setTimeout(() => setCopied(false), 1500);+ }}+ className="grid size-8 shrink-0 place-items-center rounded-full text-muted-foreground hover:bg-accent hover:text-foreground"+ aria-label="Copy"+ title="Copy"+ >+ {copied ? <Check className="size-3.5" /> : <Copy className="size-3.5" />}+ </button>+ );+ return (+ <div className="group">+ {character && first && <p className="mb-1 ml-9 text-[12px] text-muted-foreground">{character.name}</p>}+ <Row character={character} tail={tail}>+ <Bubble side="them" tail={tail} fresh={fresh}>+ <ReplyBody text={text} />+ </Bubble>+ {/* Earlier replies keep the run tight: their Copy sits beside the bubble and shows on hover. */}+ {!last && <span className="self-center opacity-0 transition-opacity group-hover:opacity-100 focus-within:opacity-100 max-sm:hidden">{copy}</span>}+ </Row>+ {last && (+ <div className={cn("mt-1 flex gap-0.5 text-muted-foreground", character && "ml-9")}>+ {copy}+ {canRetry && (+ <button type="button" onClick={onRetry} className="grid size-8 place-items-center rounded-full hover:bg-accent hover:text-foreground" aria-label="Try again" title="Try again">+ <RotateCcw className="size-3.5" />+ </button>+ )}+ </div>+ )}+ </div>+ );+}diff --git a/src/lib/chat/catalog.ts b/src/lib/chat/catalog.tsnew file mode 100644index 00000000..a58eee94--- /dev/null+++ b/src/lib/chat/catalog.ts@@ -0,0 +1,370 @@+/**+ * Fuobe Chat's fixed content: the kinds of chat, their starters, the writing tools, the Play formats and the built-in+ * characters. Pure data, safe in the browser; src/lib/chat/prompt.ts turns it into what the model reads.+ */++export type ChatKind = "chat" | "ideas" | "write" | "character" | "play";++export const CHAT_KINDS: { id: ChatKind; label: string; hint: string; placeholder: string }[] = [+ { id: "chat", label: "Chat", hint: "Ask anything, think out loud, get advice", placeholder: "Ask anything, or think out loud…" },+ { id: "ideas", label: "Ideas", hint: "Concepts you can make in one tap", placeholder: "What should we come up with ideas for?" },+ { id: "write", label: "Write", hint: "Captions, bios, rewrites and scripts", placeholder: "Paste text to rewrite, or say what to write…" },+ { id: "character", label: "Characters", hint: "Stories with characters who stay in role", placeholder: "Pick a character below to start a story" },+ { id: "play", label: "Play", hint: "Quick, fun chats worth sharing", placeholder: "Pick a game below" },+];++export const isChatKind = (v: unknown): v is ChatKind => typeof v === "string" && CHAT_KINDS.some((k) => k.id === v);++/** One-tap first messages for the open kinds. */+export const STARTERS: Record<"chat" | "ideas", string[]> = {+ chat: [+ "What should I wear to a gallery opening in November?",+ "Plan a one-day shoot in Lisbon on a small budget",+ "Explain colour grading as if I'm new to it",+ "I have a creative block. Talk me through it.",+ "Help me price my first freelance photo job",+ "How do I grow a fashion account from zero?",+ ],+ ideas: [+ "Ten reel ideas for a linen summer collection",+ "A music video for a moody synth-pop track",+ "A campaign for a perfume called Midnight Fig",+ "Thumbnails for a day-in-my-life vlog",+ "A short film about a tailor in Naples",+ "Looks for a desert editorial at golden hour",+ ],+};++// ---------------------------------------------------------------------------+// Writing tools++export interface WriteField {+ id: string;+ label: string;+ placeholder: string;+ long?: boolean;+ optional?: boolean;+}++export interface WriteTool {+ id: string;+ name: string;+ blurb: string;+ fields: WriteField[];+ tones?: string[];+ /** What the model is told the job is. */+ brief: string;+}++const TONES = ["Warm", "Bold", "Playful", "Luxury", "Minimal"];++export const WRITE_TOOLS: WriteTool[] = [+ {+ id: "caption",+ name: "Caption",+ blurb: "A post caption with a hook and hashtags",+ fields: [+ { id: "about", label: "What the post shows", placeholder: "A linen co-ord shot on a Positano terrace", long: true },+ { id: "platform", label: "Where it goes", placeholder: "Instagram, TikTok…", optional: true },+ ],+ tones: TONES,+ brief: "Write a social post caption: a strong first line that stops the scroll, one or two short lines after it, and 5–8 fitting hashtags on their own line. Then give two shorter alternatives.",+ },+ {+ id: "bio",+ name: "Bio",+ blurb: "A profile bio that says who you are",+ fields: [+ { id: "who", label: "Who you are and what you do", placeholder: "Stylist in Milan, editorial and bridal", long: true },+ { id: "where", label: "Where it goes", placeholder: "Instagram, LinkedIn, a portfolio…", optional: true },+ ],+ tones: TONES,+ brief: "Write a profile bio that fits the platform's length. Give three versions: short, medium and one with a little personality.",+ },+ {+ id: "rewrite",+ name: "Rewrite",+ blurb: "Make any text clearer, shorter or sharper",+ fields: [+ { id: "text", label: "Your text", placeholder: "Paste what you wrote", long: true },+ { id: "goal", label: "What to change", placeholder: "Shorter, friendlier, more confident…", optional: true },+ ],+ tones: TONES,+ brief: "Rewrite the text as asked. Keep its meaning and every fact. Give the rewrite first, then one line on what changed.",+ },+ {+ id: "hooks",+ name: "Hooks",+ blurb: "Opening lines for reels and videos",+ fields: [{ id: "about", label: "What the video is about", placeholder: "Three ways to style one white shirt", long: true }],+ tones: TONES,+ brief: "Write ten opening lines (hooks) for a short vertical video, each under 12 words, each a different angle: a question, a bold claim, a number, a secret, a mistake and so on.",+ },+ {+ id: "product",+ name: "Product copy",+ blurb: "A product description that sells",+ fields: [+ { id: "product", label: "The product", placeholder: "Silk slip dress, bias cut, champagne", long: true },+ { id: "details", label: "Details to include", placeholder: "Sizes, materials, care…", optional: true },+ ],+ tones: TONES,+ brief: "Write a product description: a one-line headline, a short paragraph that sells the feeling, and 3–5 bullet points with the facts.",+ },+ {+ id: "email",+ name: "Email",+ blurb: "A clear email for any situation",+ fields: [+ { id: "to", label: "Who it's to", placeholder: "A brand I want to work with" },+ { id: "point", label: "What it needs to say", placeholder: "Pitch a summer campaign shoot, my rates attached", long: true },+ ],+ tones: ["Friendly", "Formal", "Confident", "Brief"],+ brief: "Write the email with a subject line first. Keep it short, specific and easy to answer, with one clear ask.",+ },+ {+ id: "script",+ name: "Video script",+ blurb: "A short script with shots and voiceover",+ fields: [+ { id: "about", label: "What the video is about", placeholder: "A 30-second launch for a new sneaker", long: true },+ { id: "length", label: "Length", placeholder: "15 s, 30 s, 60 s…", optional: true },+ ],+ tones: TONES,+ brief: "Write a short video script as numbered shots. For each shot: what we see, and the voiceover or on-screen text. End with a call to action.",+ },+];++export const writeTool = (id: string | null | undefined) => WRITE_TOOLS.find((t) => t.id === id) ?? null;++// ---------------------------------------------------------------------------+// Play formats++export interface PlayFormat {+ id: string;+ name: string;+ blurb: string;+ /** Takes a picture (the model sees it). */+ picture?: boolean;+ /** What the person fills in before it starts; empty: it starts at once. */+ ask?: { label: string; placeholder: string };+ /** What the model is told the game is. */+ brief: string;+ /** The first message sent for the person ({input} is what they typed). */+ opener: string;+ emoji: string;+}++export const PLAY_FORMATS: PlayFormat[] = [+ {+ id: "rate-my-look",+ name: "Rate my look",+ blurb: "A stylist's honest score for your outfit",+ picture: true,+ brief:+ "You are a sharp, kind fashion editor. Score the outfit in the picture out of 10, then give: what works (two points), one change that would lift it, and a one-line verdict worth posting. Talk about the clothes, styling and colour, never the person's body.",+ opener: "Rate my look.",+ emoji: "🪞",+ },+ {+ id: "roast",+ name: "Roast me, gently",+ blurb: "A friendly roast of your habits",+ ask: { label: "Tell it about yourself", placeholder: "I own 40 black t-shirts and call them all different" },+ brief: "Write a short, affectionate roast (5–7 lines) of the person from what they share. Clever, never cruel, nothing about looks, identity or anything they can't change. End with one genuine compliment.",+ opener: "Roast me, gently: {input}",+ emoji: "🔥",+ },+ {+ id: "horoscope",+ name: "Style horoscope",+ blurb: "Today's outfit, written in the stars",+ ask: { label: "Your star sign", placeholder: "Leo" },+ brief: "Write today's playful style horoscope for the sign: the mood, a lucky colour, an outfit formula, one thing to avoid, and a one-line prophecy. Fun, specific and fashion-forward.",+ opener: "My sign is {input}. What's my style horoscope today?",+ emoji: "✨",+ },+ {+ id: "plot-twist",+ name: "Plot twist my day",+ blurb: "Your day, rewritten as a film",+ ask: { label: "What happened today", placeholder: "Missed the bus, spilled coffee, got a callback" },+ brief: "Retell the person's day as a dramatic film trailer: a title, a tagline, and 5–6 short trailer beats with a twist at the end. Cinematic, funny and warm.",+ opener: "Plot twist my day: {input}",+ emoji: "🎬",+ },+ {+ id: "debate",+ name: "Two characters argue",+ blurb: "A tiny debate on any topic",+ ask: { label: "The topic", placeholder: "Is double denim ever okay?" },+ brief:+ "Write a short, funny debate between two invented characters with strong opinions (give each a name and a one-line description first). Six to eight lines, alternating, each line punchy. End with a surprising agreement.",+ opener: "Debate: {input}",+ emoji: "🎤",+ },+ {+ id: "would-you-rather",+ name: "Would you rather",+ blurb: "Impossible choices, one at a time",+ brief: "Play would-you-rather. Ask one clever, creative or fashion-flavoured would-you-rather question at a time. After each answer, react in one line, then ask the next.",+ opener: "Let's play would you rather.",+ emoji: "🎲",+ },+];++export const playFormat = (id: string | null | undefined) => PLAY_FORMATS.find((p) => p.id === id) ?? null;++// ---------------------------------------------------------------------------+// Characters++export interface CharacterCard {+ id: string;+ name: string;+ /** One line under the name. */+ tagline: string;+ /** Who they are and how they talk (the model reads it). */+ persona: string;+ /** Where the story starts (the model reads it). */+ scenario: string;+ /** Their first message. */+ greeting: string;+ /** Mango Chilli mode only. */+ mature: boolean;+ /** The card's colours when there's no portrait. */+ accent: [string, string];+ portrait: string | null;+ builtIn: boolean;+}++export const BUILT_IN_CHARACTERS: CharacterCard[] = [+ {+ id: "sienna-vale",+ name: "Sienna Vale",+ tagline: "Fashion director, Milan. Brutally honest, secretly kind.",+ persona:+ "Sienna Vale, 38, fashion director of a Milan magazine. Dry wit, impeccable taste, zero patience for beige. Speaks in short, decisive lines, drops the odd Italian word, and gives styling advice that actually works.",+ scenario: "It's the morning of a big shoot. The user has just walked into Sienna's studio with a rail of clothes and ten minutes to impress her.",+ greeting: "*glances up from the contact sheets* Ten minutes. Show me what you brought, and please tell me none of it is beige.",+ mature: false,+ accent: ["#2b2140", "#b58b5a"],+ portrait: null,+ builtIn: true,+ },+ {+ id: "ines-ruiz",+ name: "Captain Inés Ruiz",+ tagline: "Starship captain. You're her new first officer.",+ persona:+ "Captain Inés Ruiz, 41, commands the deep-space survey ship Marisol. Calm under fire, warm with her crew, quietly haunted by her last mission. Talks like a seasoned officer: clear orders, rare smiles.",+ scenario: "The user has just come aboard as first officer, minutes before the Marisol jumps into an uncharted system where a distress signal repeats a name no one should know.",+ greeting: "Welcome aboard, Commander. *hands you a datapad* Read fast. That signal is repeating my name, and we jump in four minutes.",+ mature: false,+ accent: ["#0d1b2a", "#3a86ff"],+ portrait: null,+ builtIn: true,+ },+ {+ id: "marlowe-quinn",+ name: "Marlowe Quinn",+ tagline: "Private eye in a city that never stops raining.",+ persona:+ "Marlowe Quinn, 45, a private investigator in a rain-soaked 1940s city. Noir narrator's voice, sharp eye for lies, soft spot for lost causes. Describes the scene in moody detail and lets the user drive the investigation.",+ scenario: "Late night at Quinn's office. The user walks in out of the rain with a case: a famous model vanished the night before her first cover shoot.",+ greeting: "*rain taps the window* Door's open, kid. You look like trouble with a story attached. Sit down and tell me who's missing.",+ mature: false,+ accent: ["#1c1c1c", "#8a7650"],+ portrait: null,+ builtIn: true,+ },+ {+ id: "kai",+ name: "Kai",+ tagline: "Late-night barista and musician. Good listener.",+ persona:+ "Kai, 27, runs the night shift at a tiny café and plays guitar after closing. Easy-going, curious, funny in a quiet way. Asks good questions, remembers what you said, and never lectures.",+ scenario: "It's nearly closing time. The café is empty, the lights are low, and the user just sat down at the counter.",+ greeting: "Hey, you made it before close. *slides a mug over* On the house. Long day, or a good one?",+ mature: false,+ accent: ["#3b2a20", "#e0a458"],+ portrait: null,+ builtIn: true,+ },+ {+ id: "odette-lune",+ name: "Professor Odette Lune",+ tagline: "Teaches forbidden magic. Badly supervised.",+ persona:+ "Professor Odette Lune, 52, eccentric teacher of experimental magic at an ancient academy. Theatrical, brilliant, slightly reckless. Speaks in vivid, playful lines and turns every lesson into an adventure.",+ scenario: "The user is a new student who has just been summoned to Professor Lune's tower office after accidentally turning the library cat into a small thundercloud.",+ greeting: "*a small thundercloud rumbles on the desk* Ah, the culprit! Sit, sit. Honestly? Best transfiguration I've seen in years. Now, how do we turn him back?",+ mature: false,+ accent: ["#20123a", "#9d7bd8"],+ portrait: null,+ builtIn: true,+ },+ {+ id: "dorian-hale",+ name: "Dorian Hale",+ tagline: "Your rival designer, the night before Paris.",+ persona:+ "Dorian Hale, 34, a celebrated and insufferably charming fashion designer. Competitive, witty, theatrical, with a soft side he hides badly. Trades barbs with the user, who is his rival showing at the same Paris Fashion Week.",+ scenario: "Midnight before both shows. The user and Dorian are stuck together in a broken-down lift at the venue with one bottle of champagne.",+ greeting: "*the lift shudders and stops* Of course. Of all the designers in Paris, I get stuck with you. *raises the bottle* Truce until the doors open?",+ mature: false,+ accent: ["#2a0f1e", "#d4567c"],+ portrait: null,+ builtIn: true,+ },+ {+ id: "valentina-noir",+ name: "Valentina Noir",+ tagline: "A countess at a masquerade. Older than she looks.",+ persona:+ "Countess Valentina Noir, an ageless vampire who appears to be in her early thirties. Elegant, magnetic, teasing and dangerous. Speaks in slow, velvet sentences, flirts openly and keeps her secrets close.",+ scenario: "A masked ball in a candlelit Venetian palazzo. The user, a guest, has caught Valentina's eye across the room and she has come to find them on a quiet balcony.",+ greeting: "*steps out onto the balcony, mask in hand* You've been watching me all night. Bold. Tell me your name before I decide whether to keep you.",+ mature: true,+ accent: ["#1a0508", "#a4161a"],+ portrait: null,+ builtIn: true,+ },+ {+ id: "luca-moretti",+ name: "Luca Moretti",+ tagline: "Yacht captain on the Amalfi coast. A summer romance.",+ persona:+ "Luca Moretti, 33, captains a private yacht along the Amalfi coast. Sun-warmed, confident, playful and attentive, with a poet's streak he denies. Flirts easily and makes every moment feel like a film.",+ scenario: "Sunset off Positano. The user is the only guest who stayed on deck after dinner, and Luca has just come up from the helm with two glasses.",+ greeting: "*hands you a glass, leans on the rail beside you* Everyone else went below. Good. The sunset was getting jealous of you anyway.",+ mature: true,+ accent: ["#0b3954", "#ff8552"],+ portrait: null,+ builtIn: true,+ },+];++export const builtInCharacter = (id: string | null | undefined) => BUILT_IN_CHARACTERS.find((c) => c.id === id) ?? null;++/** Mango Chilli mode's own words, in one place. */+export const MANGO_CHILLI = {+ name: "Mango Chilli mode",+ short: "Mango Chilli",+ blurb: "Unlocks mature characters and stories for adults: romance, flirting, dark themes and strong language.",+ confirm: "I'm 18 or older and I want to see mature content.",+};++/** Limits the server and the browser share. */+export const CHAT_LIMITS = {+ messageChars: 4000,+ titleChars: 80,+ threads: 500,+ messagesPerThread: 2000,+ characters: 100,+ nameChars: 60,+ taglineChars: 120,+ personaChars: 1200,+ scenarioChars: 800,+ greetingChars: 600,+ shareMessages: 12,+};diff --git a/src/lib/chat/prompt.ts b/src/lib/chat/prompt.tsnew file mode 100644index 00000000..58604301--- /dev/null+++ b/src/lib/chat/prompt.ts@@ -0,0 +1,189 @@+import { MANGO_CHILLI, playFormat, writeTool, type CharacterCard, type ChatKind } from "./catalog";++/**+ * What Fuobe Chat's model reads: the system prompt for a chat's kind (and character, tool or game), the history that+ * fits, and the "Prompt (image): …" lines an idea ends with, which the chat turns into Make it buttons. Pure functions.+ */++export interface ChatTurn {+ role: "user" | "assistant";+ content: string;+}++export interface ChatSetup {+ kind: ChatKind;+ character?: CharacterCard | null;+ /** A writing tool's id. */+ tool?: string | null;+ /** A Play format's id. */+ play?: string | null;+ /** Mango Chilli mode is on for this chat. */+ mature: boolean;+ /** What happened earlier than the turns sent. */+ summary?: string | null;+ /** The person's first name, when known. */+ name?: string | null;+}++const BASE = `You are Fuobe Chat, the chat inside Fuobe, a creative studio for images, video and music.+Write like a sharp, warm friend who knows their stuff: plain words, short paragraphs, no filler, no preamble, no "As an AI".+Use light markdown only: **bold**, short "- " lists, and "### " headings for ideas or options.+Keep answers as short as the question allows. Ask one short question when you truly need more to go on.`;++const IDEAS = `The person wants ideas. Give 3–6 distinct ideas, each as:+### A short, vivid title+One or two lines on the idea and why it works.+Prompt (image): one rich line describing the shot to make (subject, setting, light, lens, mood).+Use "Prompt (video):" instead for a moving idea (describe the motion and camera move in order), and "Prompt (music):" for a song or track (genre, mood, instruments, tempo).+Every idea ends with exactly one Prompt line.`;++const CHAT_EXTRA = `When an idea for an image, a video or a song comes up, you may end with one line "Prompt (image): …" (or video, or music) so the person can make it in one tap.`;++const CHARACTER_RULES = `Stay in character at all times and write as the character, in the first person, in present tense.+Put actions and scene details in *asterisks*. Keep replies to one to three short paragraphs and leave room for the user to act.+Never write the user's words or decide their actions. Move the story forward with a hook, a choice or a question.+Every character in the story is an adult. No character is a real person.+If the user writes in (( double brackets )), step out of the story briefly and answer as a helpful narrator.`;++const MATURE = `${MANGO_CHILLI.name} is on: the user is an adult who chose mature content. Romance, flirting, sensual scenes, dark themes and strong language are welcome when the story calls for them. Every character stays an adult.`;++const GENERAL = `Keep content suitable for a general audience: romance and danger are fine, explicit content is not.`;++/** The system prompt for a chat. */+export function systemPrompt(s: ChatSetup): string {+ const parts: string[] = [];+ if (s.kind === "character" && s.character) {+ const c = s.character;+ parts.push(`You are ${c.name}. ${c.persona}`);+ if (c.scenario) parts.push(`Where the story starts: ${c.scenario}`);+ parts.push(CHARACTER_RULES);+ } else {+ parts.push(BASE);+ if (s.kind === "ideas") parts.push(IDEAS);+ else if (s.kind === "write") {+ const t = writeTool(s.tool);+ parts.push(+ t+ ? `The person is using the ${t.name} tool. ${t.brief} Give the finished text first, ready to copy, with no lead-in. They may ask for changes after.`+ : `The person wants help writing. Give the finished text first, ready to copy, with no lead-in, then offer one short tweak.`,+ );+ } else if (s.kind === "play") {+ const p = playFormat(s.play);+ if (p) parts.push(p.brief, "Keep it fun, quick and worth sharing. Never be mean about anything the person can't change.");+ } else parts.push(CHAT_EXTRA);+ }+ parts.push(s.mature ? MATURE : GENERAL);+ if (s.name) parts.push(`The person's name is ${s.name}.`);+ if (s.summary) parts.push(`What happened earlier in this chat (older messages aren't shown): ${s.summary}`);+ return parts.join("\n\n");+}++/**+ * The newest turns that fit in `budget` characters, oldest first, starting on a user turn when it can. The last turn+ * always goes, cut to the budget if it must be. `dropped`: how many older turns were left out (a summary covers them).+ */+export function fitHistory(turns: ChatTurn[], budget: number): { turns: ChatTurn[]; dropped: number } {+ const out: ChatTurn[] = [];+ let used = 0;+ for (let i = turns.length - 1; i >= 0; i--) {+ const t = turns[i];+ const cost = t.content.length + 16;+ if (out.length > 0 && used + cost > budget) break;+ out.unshift(out.length === 0 && cost > budget ? { ...t, content: t.content.slice(-Math.max(200, budget - 16)) } : t);+ used += cost;+ }+ // A history that starts with the assistant reads fine for a character (the greeting), but a lone reply mid-chat+ // with no question before it doesn't: drop it when a user turn follows.+ while (out.length > 1 && out[0].role === "assistant" && out[0] !== turns[0]) out.shift();+ return { turns: out, dropped: turns.length - out.length };+}++/**+ * One text for a model that takes a single message (the free helper before it took chat turns): the history as a+ * transcript, then the ask to write the next reply.+ */+export function transcript(turns: ChatTurn[], speaker = "You"): string {+ const lines = turns.map((t) => `${t.role === "user" ? "User" : speaker}: ${t.content}`);+ return `The conversation so far:\n\n${lines.join("\n\n")}\n\nWrite ${speaker}'s next reply to the user's last message. Write only the reply, without a "${speaker}:" label.`;+}++/** A reply as it should be kept: no reasoning block, no speaker label the model added. */+export function tidyReply(text: string, speaker?: string): string {+ let t = text.replace(/<think>[\s\S]*?<\/think>/g, "").trim();+ const label = new RegExp(`^(?:${["You", "Assistant", "Fuobe Chat", speaker].filter(Boolean).map((s) => s!.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})\\s*:\\s*`, "i");+ t = t.replace(label, "");+ return t.trim();+}++export type MakeStudio = "image" | "video" | "music";++export interface MakeIt {+ studio: MakeStudio;+ prompt: string;+}++const PROMPT_LINE = /^\s*(?:[-*]\s*)?\**\s*prompt\s*(?:\(\s*(image|video|music|song|track|photo|picture|clip)\s*\))?\s*\**\s*:\s*\**\s*(.+?)\s*\**\s*$/i;++const STUDIO_OF: Record<string, MakeStudio> = { image: "image", photo: "image", picture: "image", video: "video", clip: "video", music: "music", song: "music", track: "music" };++export type ReplyPart = { kind: "text"; text: string } | { kind: "make"; make: MakeIt };++/** A reply split into its prose and the Make it prompts in it, in order. */+export function splitMakeIts(text: string): ReplyPart[] {+ const out: ReplyPart[] = [];+ let buf: string[] = [];+ const flush = () => {+ const t = buf.join("\n").trim();+ if (t) out.push({ kind: "text", text: t });+ buf = [];+ };+ for (const line of text.split("\n")) {+ const m = PROMPT_LINE.exec(line);+ if (m && m[2].length >= 8) {+ flush();+ out.push({ kind: "make", make: { studio: STUDIO_OF[(m[1] ?? "image").toLowerCase()] ?? "image", prompt: m[2].replace(/^["“]|["”]$/g, "") } });+ } else buf.push(line);+ }+ flush();+ return out;+}++/** Where Make it opens: the studio with the prompt filled in (src/lib/composer.ts HANDOFF_PARAMS). */+export function makeItHref(m: MakeIt): string {+ const path = m.studio === "video" ? "/video" : m.studio === "music" ? "/audio/music" : "/image";+ return `${path}?prompt=${encodeURIComponent(m.prompt.slice(0, 2000))}`;+}++/** A chat's title from its first message: the first line, cut at a word near 60 characters. */+export function titleFrom(text: string): string {+ const line = text.replace(/\s+/g, " ").trim();+ if (line.length <= 60) return line || "New chat";+ const cut = line.slice(0, 60);+ const sp = cut.lastIndexOf(" ");+ return `${(sp > 30 ? cut.slice(0, sp) : cut).replace(/[,.;:!?-]+$/, "")}…`;+}++/** A writing tool's form, as the first message. */+export function toolMessage(toolId: string, values: Record<string, string>, tone?: string | null): string {+ const t = writeTool(toolId);+ if (!t) return Object.values(values).join("\n");+ const lines = t.fields.filter((f) => values[f.id]?.trim()).map((f) => `${f.label}: ${values[f.id].trim()}`);+ if (tone) lines.push(`Tone: ${tone}`);+ return lines.join("\n");+}++/** A Play format's first message. */+export function playMessage(playId: string, input: string): string {+ const p = playFormat(playId);+ if (!p) return input;+ return p.opener.replace("{input}", input.trim());+}++/** The words that ask for a summary of older turns, to keep a long chat coherent. */+export function summaryAsk(previous: string | null | undefined, turns: ChatTurn[], speaker = "Assistant"): { system: string; user: string } {+ return {+ system:+ "You keep notes on a conversation so it can continue later. Write a compact summary in under 140 words: names, facts about the user, preferences, decisions, and for a story the current scene, relationships and open threads. Plain sentences, no headings.",+ user: `${previous ? `Summary so far: ${previous}\n\n` : ""}New messages to fold in:\n\n${turns.map((t) => `${t.role === "user" ? "User" : speaker}: ${t.content}`).join("\n\n")}`,+ };+}diff --git a/src/lib/chat/share.ts b/src/lib/chat/share.tsnew file mode 100644index 00000000..08b20d23--- /dev/null+++ b/src/lib/chat/share.ts@@ -0,0 +1,11 @@+/**+ * A shared chat's public paths: /c/<token> (its page), /c/<token>/portrait (its character's picture) and its link+ * preview picture (opengraph-image). The proxy lets exactly these through without a session; the page and routes+ * check the token themselves and answer 404 for one that isn't live.+ */+export const CHAT_SHARE_PATH = /^\/c\/([A-Za-z0-9_-]{32})(?:\/(?:portrait|opengraph-image(?:-[\w-]+)?))?$/;++export const chatShareRoute = (pathname: string): boolean => CHAT_SHARE_PATH.test(pathname);++/** The browser remembers that this visitor said they're 18 or older (shared Mango Chilli chats). */+export const ADULT_OK_KEY = "fuobe:chat-adult-ok";diff --git a/src/lib/chat/types.ts b/src/lib/chat/types.tsnew file mode 100644index 00000000..68962113--- /dev/null+++ b/src/lib/chat/types.ts@@ -0,0 +1,71 @@+import type { CharacterCard, ChatKind } from "./catalog";++/** What the chat's API sends the browser. */++export interface ChatMessage {+ id: string;+ role: "user" | "assistant";+ content: string;+ /** A picture the person sent with it (their own file). */+ image: string | null;+ createdAt: number;+}++export interface ChatThreadSummary {+ id: string;+ kind: ChatKind;+ title: string;+ characterId: string | null;+ /** The character's name and look, for the list. */+ character: Pick<CharacterCard, "id" | "name" | "accent" | "portrait"> | null;+ tool: string | null;+ play: string | null;+ mature: boolean;+ /** The last message, cut short. */+ preview: string;+ updatedAt: number;+}++export interface ChatThreadView extends ChatThreadSummary {+ messages: ChatMessage[];+ characterCard: CharacterCard | null;+ /** The share link's token, while one is live. */+ shareToken: string | null;+}++/** Where a reply comes from. */+export type ChatEngine = "site" | "key";++export interface ChatMe {+ /** The free model can answer this person now. */+ site: boolean;+ /** The install has a free model at all (it may be resting). */+ siteKnown: boolean;+ /** Their own OpenRouter key, when saved. */+ key: { last4: string; model: string } | null;+ engine: ChatEngine;+ mature: boolean;+ owner: boolean;+}++/** One line of a reply's stream (NDJSON). */+export type ChatEvent =+ | { type: "user"; message: ChatMessage }+ | { type: "queue"; position: number }+ | { type: "text"; text: string }+ | { type: "done"; message: ChatMessage; title: string }+ | { type: "error"; code: ChatErrorCode; message: string; retryAfterS?: number };++export type ChatErrorCode = "busy" | "limit" | "blocked" | "failed" | "sign-in" | "no-model" | "key-refused" | "too-long";++/** A shared chat as its public page shows it: a copy made when it was shared. */+export interface ChatShareSnapshot {+ title: string;+ kind: ChatKind;+ mature: boolean;+ character: Pick<CharacterCard, "id" | "name" | "tagline" | "accent" | "builtIn"> & { portrait: boolean } | null;+ /** The play format or writing tool, for the label. */+ label: string | null;+ messages: { role: "user" | "assistant"; content: string }[];+ createdAt: number;+}diff --git a/src/lib/guest-access.ts b/src/lib/guest-access.tsindex 54b8a1ab..0db4bcf3 100644--- a/src/lib/guest-access.ts+++ b/src/lib/guest-access.ts@@ -400,6 +400,9 @@ export const ACCOUNT_PROJECT_ROUTES: RegExp[] = [/^\/api\/explainer(\/document)?$/,/^\/api\/content-factory\/series(\/[^/]+(\/(episodes|generate|read))?)?$/,/^\/api\/starters\/faceless\.[^/]+$/,+ // Fuobe Chat: its own chats, characters and chat settings (src/server/chat/store.ts). Replies run on the install's free+ // text helper (which counts each account's use) or on the account's own OpenRouter key, never the studio's keys.+ /^\/api\/chat\/(me|key|threads(\/[^/]+(\/(reply|share))?)?|characters(\/[^/]+)?)$/,];export const accountProjectRoute = (pathname: string): boolean => ACCOUNT_PROJECT_ROUTES.some((r) => r.test(pathname));diff --git a/src/proxy.ts b/src/proxy.tsindex 6f8ec887..de85a45c 100644--- a/src/proxy.ts+++ b/src/proxy.ts@@ -3,6 +3,7 @@ import { APPS } from "@/lib/catalog/apps";import { FORMER_HOME, modeHref, type HubKind } from "@/lib/hubs";import { hiddenStarterPage, recordForPath, unknownHubMode, unknownStarterPage } from "@/lib/record-pages";import { countsAsView, SHARE_VIEW_HEADER, shareRoute } from "@/lib/share";+import { chatShareRoute } from "@/lib/chat/share";import {ACCOUNT_LIBRARY_MESSAGE,accountGeneration,@@ -406,6 +407,8 @@ export function proxy(request: NextRequest) {const read = request.method === "GET" || request.method === "HEAD";const share = read && shareRoute(pathname);if (share) return openShare(request, share.token, !!share.file);+ // A shared chat (Fuobe Chat) is public too: its page, its portrait and its link preview, each checking the token.+ if (read && chatShareRoute(pathname)) return NextResponse.next();// Any other /s/ link is no share: the same "link unavailable" 404 as an unknown token.if (read && pathname.startsWith("/s/")) {const res = shareGone(request);diff --git a/src/server/account-sweep.ts b/src/server/account-sweep.tsindex 22fe13ff..5f3fccda 100644--- a/src/server/account-sweep.ts+++ b/src/server/account-sweep.ts@@ -4,6 +4,7 @@ import path from "node:path";import { RETENTION_MS, runAccountDeletedHooks } from "./account-files";import { deleteAccountCanvases } from "./account-canvas";import { deleteAccountProjects } from "./account-projects";+import { deleteAccountChat } from "./chat/store";import { deleteAccountCinema } from "./cinema";import { deleteAccountSeries } from "./content-factory";import { deleteAccountFaceless } from "./faceless";@@ -57,6 +58,7 @@ export async function purgeAccount(id: string): Promise<{ runs: number; files: ndeleteAccountSeries(id);deleteAccountFaceless(id);deleteAccountProjects(id);+ deleteAccountChat(id);forgetAccountPresses(id);await runAccountDeletedHooks(id);return { runs, files: files.length };diff --git a/src/server/chat/backend.ts b/src/server/chat/backend.tsnew file mode 100644index 00000000..7e569d6b--- /dev/null+++ b/src/server/chat/backend.ts@@ -0,0 +1,182 @@+import "server-only";+import { fitHistory, summaryAsk, tidyReply, transcript, type ChatTurn } from "@/lib/chat/prompt";+import type { ChatEngine, ChatErrorCode } from "@/lib/chat/types";+import { readSse } from "../llm/sse";+import { runAsTenant } from "../tenant";+import { askHelper, freeHelperOn, helperKnown, HELPER_LIMITS, type HelperAnswer } from "../text-helper";++/**+ * Where Fuobe Chat's replies come from:+ * - "site": the install's free text helper (src/server/text-helper.ts), the open model in the workers' text slots. It+ * takes one message today, so the history goes as a transcript that fits its limit.+ * - "key": the person's own OpenRouter key, streamed, with the history as real turns.+ * Nothing here throws for a model's trouble: the answer says what went wrong, in words for the person.+ */++export interface ReplyAsk {+ /** An account's id, or "owner". */+ who: string;+ system: string;+ turns: ChatTurn[];+ /** Who replies, for a transcript ("Sienna Vale"; "You" for the assistant). */+ speaker: string;+ /** A picture sent with the newest turn. */+ image?: { data: Buffer; contentType: string } | null;+ temperature?: number;+ signal?: AbortSignal;+ /** The reply so far, as it is written (a model that doesn't stream says it once, at the end). */+ onText?: (soFar: string) => void;+}++export type ReplyAnswer = { text: string; dropped: number } | { error: ChatErrorCode; message: string; retryAfterS?: number };++export const CHAT_WORDS: Record<ChatErrorCode, string> = {+ busy: "The free chat model is busy or resting right now. Try again in a moment.",+ limit: "That's a lot of messages in a short time. Take a breather and try again soon.",+ blocked: "This message can't be answered here.",+ failed: "The reply didn't finish. Try again.",+ "sign-in": "Create a free account to chat.",+ "no-model": "The free chat model isn't switched on here yet. Add your own OpenRouter key in chat settings to chat now.",+ "key-refused": "OpenRouter didn't accept your key. Check it in chat settings.",+ "too-long": "This chat is as long as a chat can be. Start a new one to keep going.",+};++const asTenant = <T,>(who: string, fn: () => T): T => (who === "owner" ? fn() : runAsTenant({ kind: "account", id: who }, fn));++/** Can the free model answer this person now (and is there one at all)? */+export function siteStatus(who: string): { on: boolean; known: boolean } {+ return asTenant(who, () => ({ on: freeHelperOn(Date.now(), {}), known: helperKnown() }));+}++/** History room for the free helper: its message limit, less the transcript's own words. */+const SITE_BUDGET = HELPER_LIMITS.userChars - 600;+/** History room for a hosted model through the person's key (its context is far larger). */+const KEY_BUDGET = 24_000;++function fromHelper(a: Exclude<HelperAnswer, { text: string }>): ReplyAnswer {+ const code: ChatErrorCode = a.error === "sign-in" ? "sign-in" : a.error === "limit" ? "limit" : a.error === "blocked" ? "blocked" : a.error === "busy" ? "busy" : "failed";+ const message = code === "limit" && a.retryAfterS ? `That's a lot of messages in a short time. Try again in ${a.retryAfterS < 90 ? `${a.retryAfterS} s` : `${Math.ceil(a.retryAfterS / 60)} min`}.` : a.error === "blocked" && a.message ? a.message : CHAT_WORDS[code];+ return { error: code, message, ...(a.retryAfterS ? { retryAfterS: a.retryAfterS } : {}) };+}++async function siteReply(ask: ReplyAsk): Promise<ReplyAnswer> {+ const fit = fitHistory(ask.turns, SITE_BUDGET);+ return asTenant(ask.who, async () => {+ if (!freeHelperOn(Date.now(), { vision: !!ask.image })) {+ return { error: helperKnown() ? "busy" : "no-model", message: helperKnown() ? CHAT_WORDS.busy : CHAT_WORDS["no-model"] } as ReplyAnswer;+ }+ const a = await askHelper({+ task: "write",+ system: ask.system,+ user: transcript(fit.turns, ask.speaker),+ ...(ask.image && { images: [ask.image] }),+ signal: ask.signal,+ });+ if ("error" in a) return fromHelper(a);+ const text = tidyReply(a.text, ask.speaker);+ if (!text) return { error: "failed", message: CHAT_WORDS.failed } as ReplyAnswer;+ // Whole, with no text on the way: the browser shows it as if written.+ return { text, dropped: fit.dropped };+ });+}++const OPENROUTER = "https://openrouter.ai/api/v1";++/** Their key, checked with OpenRouter (a free call that runs nothing). */+export async function checkOpenRouterKey(key: string, signal?: AbortSignal): Promise<"ok" | "refused" | "unreachable"> {+ try {+ const r = await fetch(`${OPENROUTER}/key`, { headers: { Authorization: `Bearer ${key}` }, redirect: "error", signal: signal ?? AbortSignal.timeout(10_000) });+ return r.ok ? "ok" : r.status === 401 || r.status === 403 ? "refused" : "unreachable";+ } catch {+ return "unreachable";+ }+}++async function keyReply(ask: ReplyAsk, key: { key: string; model: string }): Promise<ReplyAnswer> {+ const fit = fitHistory(ask.turns, KEY_BUDGET);+ const messages: unknown[] = [{ role: "system", content: ask.system }];+ fit.turns.forEach((t, i) => {+ const last = i === fit.turns.length - 1;+ if (last && t.role === "user" && ask.image) {+ messages.push({+ role: "user",+ content: [+ { type: "text", text: t.content },+ { type: "image_url", image_url: { url: `data:${ask.image.contentType};base64,${ask.image.data.toString("base64")}` } },+ ],+ });+ } else messages.push({ role: t.role, content: t.content });+ });+ let res: Response;+ try {+ res = await fetch(`${OPENROUTER}/chat/completions`, {+ method: "POST",+ redirect: "error",+ headers: { Authorization: `Bearer ${key.key}`, "Content-Type": "application/json", "HTTP-Referer": "https://fuobe.com", "X-Title": "Fuobe Chat" },+ body: JSON.stringify({ model: key.model, messages, stream: true, max_tokens: 1200, ...(ask.temperature !== undefined && { temperature: ask.temperature }) }),+ signal: ask.signal,+ });+ } catch {+ return { error: "failed", message: "Couldn't reach OpenRouter. Try again in a moment." };+ }+ if (!res.ok || !res.body) {+ if (res.status === 401 || res.status === 403) return { error: "key-refused", message: CHAT_WORDS["key-refused"] };+ if (res.status === 402) return { error: "failed", message: "Your OpenRouter account is out of credits for this model. Top it up, or pick a free model in chat settings." };+ if (res.status === 429) return { error: "limit", message: "OpenRouter says this model is busy or your limit is reached. Try again soon, or pick another model in chat settings." };+ if (res.status === 404 || res.status === 400) return { error: "failed", message: `OpenRouter couldn't run "${key.model}". Pick another model in chat settings.` };+ return { error: "failed", message: "OpenRouter couldn't answer. Try again in a moment." };+ }+ let text = "";+ let problem: string | null = null;+ try {+ await readSse(+ res.body,+ (payload) => {+ if (payload === "[DONE]") return "done";+ try {+ const j = JSON.parse(payload) as { choices?: { delta?: { content?: string } }[]; error?: { message?: string } };+ if (j.error) {+ problem = typeof j.error.message === "string" ? j.error.message.slice(0, 200) : "OpenRouter stopped the reply.";+ return "done";+ }+ const d = j.choices?.[0]?.delta?.content;+ if (typeof d === "string" && d) {+ text += d;+ ask.onText?.(text);+ }+ } catch {+ // A line that isn't JSON (a keep-alive): skip it.+ }+ },+ 60_000,+ );+ } catch {+ if (!text) return { error: "failed", message: CHAT_WORDS.failed };+ }+ const tidy = tidyReply(text, ask.speaker);+ if (!tidy) return { error: "failed", message: problem ? `OpenRouter: ${problem}` : CHAT_WORDS.failed };+ return { text: tidy, dropped: fit.dropped };+}++/** A reply from the engine the person picked. */+export async function chatReply(engine: ChatEngine, ask: ReplyAsk, key: { key: string; model: string } | null): Promise<ReplyAnswer> {+ if (engine === "key") {+ if (!key) return { error: "key-refused", message: "Your saved key can't be opened any more. Add it again in chat settings." };+ return keyReply(ask, key);+ }+ return siteReply(ask);+}++/** Fold older turns into the chat's summary, on the free model (not counted against the person: it's housekeeping). Null on any trouble. */+export async function summarize(who: string, previous: string | null, turns: ChatTurn[], speaker: string, key: { key: string; model: string } | null): Promise<string | null> {+ const s = summaryAsk(previous, turns, speaker);+ if (key) {+ const a = await keyReply({ who, system: s.system, turns: [{ role: "user", content: s.user.slice(-KEY_BUDGET) }], speaker: "Notes", temperature: 0.3 }, key);+ return "text" in a ? a.text.slice(0, 2000) : null;+ }+ return asTenant(who, async () => {+ if (!freeHelperOn()) return null;+ const a = await askHelper({ task: "write", system: s.system, user: s.user.slice(-HELPER_LIMITS.userChars), counted: false });+ return "text" in a ? tidyReply(a.text).slice(0, 2000) : null;+ });+}diff --git a/src/server/chat/files.ts b/src/server/chat/files.tsnew file mode 100644index 00000000..fe1209cc--- /dev/null+++ b/src/server/chat/files.ts@@ -0,0 +1,58 @@+import "server-only";+import { localHead, readRef, saveFile } from "../storage";+import { runAsTenant } from "../tenant";++/**+ * Pictures in Fuobe Chat: one sent with a message ("Rate my look") and a character's portrait. Each is one of the+ * person's own stored files (an /api/files/ URL), read as them, so nobody points a chat at another account's file.+ */++const FILE_REF = /^\/api\/files\/[\w./-]{1,300}$/;+const PICTURE = /^image\/(png|jpeg|webp|gif)$/;++const asWho = <T,>(who: string, fn: () => T): T => (who === "owner" ? fn() : runAsTenant({ kind: "account", id: who }, fn));++/** The ref, when it is a picture this person owns; else null. */+export function ownPicture(who: string, ref: unknown): string | null {+ if (typeof ref !== "string" || !FILE_REF.test(ref) || ref.includes("..")) return null;+ const head = asWho(who, () => localHead(ref, 64));+ if (!head) return null;+ const png = head[0] === 0x89 && head[1] === 0x50;+ const jpeg = head[0] === 0xff && head[1] === 0xd8;+ const webp = head.subarray(8, 12).toString("latin1") === "WEBP";+ const gif = head.subarray(0, 3).toString("latin1") === "GIF";+ return png || jpeg || webp || gif ? ref : null;+}++/** The bytes of one of their pictures, or null. */+export async function readPicture(who: string, ref: string): Promise<{ data: Buffer; contentType: string } | null> {+ if (!ownPicture(who, ref)) return null;+ try {+ const f = await asWho(who, () => readRef(ref));+ return PICTURE.test(f.contentType) ? { data: f.data, contentType: f.contentType } : null;+ } catch {+ return null;+ }+}++/** A picture read for anyone (a shared chat's portrait): no account check. Only for refs a share row holds. */+export async function readSharedPicture(ref: string): Promise<{ data: Buffer; contentType: string } | null> {+ if (!FILE_REF.test(ref) || ref.includes("..")) return null;+ try {+ const f = await readRef(ref);+ return PICTURE.test(f.contentType) ? { data: f.data, contentType: f.contentType } : null;+ } catch {+ return null;+ }+}++/** A copy of a shared portrait as this person's own file (making a character from a shared chat). */+export async function copyPicture(who: string, ref: string): Promise<string | null> {+ const f = await readSharedPicture(ref);+ if (!f) return null;+ try {+ return saveFile({ data: f.data, contentType: f.contentType, name: "portrait", source: "upload", ...(who !== "owner" && { accountId: who }) }).url;+ } catch {+ return null;+ }+}diff --git a/src/server/chat/http.ts b/src/server/chat/http.tsnew file mode 100644index 00000000..c7cfa4be--- /dev/null+++ b/src/server/chat/http.ts@@ -0,0 +1,40 @@+import "server-only";+import { GUEST_HEADER, GUEST_RUN_MESSAGE } from "@/lib/guest-access";+import { requestAccount, requestViewer } from "../auth";+import { hit } from "../rate";+import { ChatError } from "./store";++/**+ * Who a chat request is for. An account reaches its own chats (the proxy lets it through: ACCOUNT_PROJECT_ROUTES); the+ * owner has their own, under "owner"; a guest is refused with the sign-up card.+ */+export function chatViewer(request: Request): { who: string; owner: boolean } | null {+ const account = requestAccount(request);+ if (account) return { who: account.id, owner: false };+ return requestViewer(request).kind === "owner" ? { who: "owner", owner: true } : null;+}++export const signUp = () => Response.json({ error: GUEST_RUN_MESSAGE, code: "sign-in" }, { status: 401, headers: { [GUEST_HEADER]: "1" } });++/** Changes a minute per person (saves, renames, new chats): a runaway tab can't fill the database. */+export function tooOften(who: string, what = "changes", limit = 60): Response | null {+ if (who === "owner") return null;+ const r = hit(`chat-${what}:${who}`, limit, 60_000);+ return r.ok ? null : Response.json({ error: "That's a lot at once. Wait a moment, then try again.", code: "limit" }, { status: 429, headers: { "Retry-After": String(r.retryAfterS) } });+}++export function refused(e: unknown): Response {+ if (e instanceof ChatError) return Response.json({ error: e.message, ...(e.code && { code: e.code }) }, { status: e.status });+ throw e;+}++export async function body(request: Request): Promise<Record<string, unknown>> {+ try {+ const b = await request.json();+ return b && typeof b === "object" && !Array.isArray(b) ? (b as Record<string, unknown>) : {};+ } catch {+ return {};+ }+}++export const gone = () => Response.json({ error: "That chat is gone." }, { status: 404 });diff --git a/src/server/chat/schemas.ts b/src/server/chat/schemas.tsnew file mode 100644index 00000000..0735b33c--- /dev/null+++ b/src/server/chat/schemas.ts@@ -0,0 +1,14 @@+import "server-only";+import { z } from "zod";++/** A character as the browser sends it (src/server/chat/store.ts cleans and limits each field). */+export const CharacterBody = z.object({+ name: z.string().max(200).optional(),+ tagline: z.string().max(400).optional(),+ persona: z.string().max(4000).optional(),+ scenario: z.string().max(4000).optional(),+ greeting: z.string().max(2000).optional(),+ mature: z.boolean().optional(),+ accent: z.tuple([z.string(), z.string()]).optional(),+ portrait: z.string().max(400).nullish(),+});diff --git a/src/server/chat/store.ts b/src/server/chat/store.tsnew file mode 100644index 00000000..07a75441--- /dev/null+++ b/src/server/chat/store.ts@@ -0,0 +1,514 @@+import "server-only";+import crypto from "node:crypto";+import { BUILT_IN_CHARACTERS, builtInCharacter, CHAT_LIMITS, isChatKind, playFormat, writeTool, type CharacterCard, type ChatKind } from "@/lib/chat/catalog";+import { titleFrom } from "@/lib/chat/prompt";+import type { ChatEngine, ChatMessage, ChatShareSnapshot, ChatThreadSummary, ChatThreadView } from "@/lib/chat/types";+import { db } from "../db";+import { open as openSealed, seal } from "../secret-box";++/**+ * Fuobe Chat's rows (src/server/db.ts CHAT_TABLES). Every read and change names the chat's owner (`who`: an account's id,+ * or "owner"), so one account never reaches another's chats, characters or settings.+ */++export class ChatError extends Error {+ constructor(+ message: string,+ readonly status = 400,+ readonly code?: string,+ ) {+ super(message);+ }+}++const newId = (prefix: string) => `${prefix}_${crypto.randomBytes(9).toString("base64url")}`;+const clip = (s: unknown, n: number) => (typeof s === "string" ? s.replace(/\r\n/g, "\n").trim().slice(0, n) : "");++// ---------------------------------------------------------------------------+// Characters++interface CharacterRow {+ id: string;+ account_id: string;+ name: string;+ tagline: string;+ persona: string;+ scenario: string;+ greeting: string;+ mature: number;+ accent: string;+ portrait_url: string | null;+ created_at: number;+ updated_at: number;+}++const HEX = /^#[0-9a-f]{6}$/i;++function accentOf(raw: unknown): [string, string] {+ try {+ const a = typeof raw === "string" ? JSON.parse(raw) : raw;+ if (Array.isArray(a) && a.length === 2 && a.every((x) => typeof x === "string" && HEX.test(x))) return [a[0], a[1]];+ } catch {+ // An unreadable value: the default below.+ }+ return ["#241a3a", "#6a5ee7"];+}++const fromCharacterRow = (r: CharacterRow): CharacterCard => ({+ id: r.id,+ name: r.name,+ tagline: r.tagline,+ persona: r.persona,+ scenario: r.scenario,+ greeting: r.greeting,+ mature: !!r.mature,+ accent: accentOf(r.accent),+ portrait: r.portrait_url,+ builtIn: false,+});++/** The built-in characters and this person's own, newest own first. Mature ones only while Mango Chilli is on. */+export function listCharacters(who: string, mature: boolean): CharacterCard[] {+ const own = (db().prepare("SELECT * FROM account_chat_characters WHERE account_id = ? ORDER BY updated_at DESC").all(who) as CharacterRow[]).map(fromCharacterRow);+ return [...own, ...BUILT_IN_CHARACTERS].filter((c) => mature || !c.mature);+}++/** A character this person may chat with: a built-in one, or one of their own. */+export function getCharacter(who: string, id: string | null | undefined): CharacterCard | null {+ if (!id) return null;+ const b = builtInCharacter(id);+ if (b) return b;+ const r = db().prepare("SELECT * FROM account_chat_characters WHERE id = ? AND account_id = ?").get(id, who) as CharacterRow | undefined;+ return r ? fromCharacterRow(r) : null;+}++export interface CharacterInput {+ name?: unknown;+ tagline?: unknown;+ persona?: unknown;+ scenario?: unknown;+ greeting?: unknown;+ mature?: unknown;+ accent?: unknown;+ portrait?: unknown;+}++function cleanCharacter(input: CharacterInput, before?: CharacterCard) {+ const L = CHAT_LIMITS;+ const name = input.name === undefined && before ? before.name : clip(input.name, L.nameChars);+ const persona = input.persona === undefined && before ? before.persona : clip(input.persona, L.personaChars);+ if (!name) throw new ChatError("Give your character a name.");+ if (persona.length < 10) throw new ChatError("Say a little about who your character is: how they talk and what they're like.");+ const greeting = input.greeting === undefined && before ? before.greeting : clip(input.greeting, L.greetingChars);+ return {+ name,+ persona,+ tagline: input.tagline === undefined && before ? before.tagline : clip(input.tagline, L.taglineChars),+ scenario: input.scenario === undefined && before ? before.scenario : clip(input.scenario, L.scenarioChars),+ greeting: greeting || `*${name} looks up* Oh, hello. I wasn't expecting anyone.`,+ mature: input.mature === undefined && before ? before.mature : input.mature === true,+ accent: input.accent === undefined && before ? before.accent : accentOf(input.accent),+ portrait: input.portrait === undefined && before ? before.portrait : typeof input.portrait === "string" && input.portrait ? input.portrait : null,+ };+}++export function createCharacter(who: string, input: CharacterInput): CharacterCard {+ const n = (db().prepare("SELECT COUNT(*) AS n FROM account_chat_characters WHERE account_id = ?").get(who) as { n: number }).n;+ if (n >= CHAT_LIMITS.characters) throw new ChatError(`You have ${CHAT_LIMITS.characters} characters, the most there can be. Delete one to make another.`, 409);+ const c = cleanCharacter(input);+ const id = newId("ch");+ const now = Date.now();+ db()+ .prepare(+ "INSERT INTO account_chat_characters (id, account_id, name, tagline, persona, scenario, greeting, mature, accent, portrait_url, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",+ )+ .run(id, who, c.name, c.tagline, c.persona, c.scenario, c.greeting, c.mature ? 1 : 0, JSON.stringify(c.accent), c.portrait, now, now);+ return getCharacter(who, id)!;+}++export function updateCharacter(who: string, id: string, input: CharacterInput): CharacterCard {+ const before = getCharacter(who, id);+ if (!before || before.builtIn) throw new ChatError("That character isn't one of yours.", 404);+ const c = cleanCharacter(input, before);+ db()+ .prepare("UPDATE account_chat_characters SET name = ?, tagline = ?, persona = ?, scenario = ?, greeting = ?, mature = ?, accent = ?, portrait_url = ?, updated_at = ? WHERE id = ? AND account_id = ?")+ .run(c.name, c.tagline, c.persona, c.scenario, c.greeting, c.mature ? 1 : 0, JSON.stringify(c.accent), c.portrait, Date.now(), id, who);+ return getCharacter(who, id)!;+}++/** Delete one of their characters. Its chats stay, and carry on without its card. */+export function deleteCharacter(who: string, id: string): boolean {+ return db().prepare("DELETE FROM account_chat_characters WHERE id = ? AND account_id = ?").run(id, who).changes === 1;+}++// ---------------------------------------------------------------------------+// Chats++interface ThreadRow {+ id: string;+ account_id: string;+ kind: string;+ title: string;+ character_id: string | null;+ tool: string | null;+ play: string | null;+ mature: number;+ summary: string | null;+ summary_upto: number;+ share_token: string | null;+ created_at: number;+ updated_at: number;+}++interface MessageRow {+ id: string;+ thread_id: string;+ account_id: string;+ seq: number;+ role: "user" | "assistant";+ content: string;+ image_url: string | null;+ created_at: number;+}++const fromMessageRow = (r: MessageRow): ChatMessage => ({ id: r.id, role: r.role, content: r.content, image: r.image_url, createdAt: r.created_at });++function summaryOf(who: string, r: ThreadRow, last?: string): ChatThreadSummary {+ const c = getCharacter(who, r.character_id);+ return {+ id: r.id,+ kind: isChatKind(r.kind) ? r.kind : "chat",+ title: r.title,+ characterId: r.character_id,+ character: c ? { id: c.id, name: c.name, accent: c.accent, portrait: c.portrait } : null,+ tool: r.tool,+ play: r.play,+ mature: !!r.mature,+ preview: (last ?? "").replace(/\s+/g, " ").slice(0, 140),+ updatedAt: r.updated_at,+ };+}++/** Their chats, newest first, with the last message of each. Mature chats only while Mango Chilli is on. */+export function listThreads(who: string, o: { mature: boolean; q?: string; limit?: number } = { mature: false }): ChatThreadSummary[] {+ const q = o.q?.trim().toLowerCase();+ const rows = db()+ .prepare(+ `SELECT t.*, (SELECT content FROM account_chat_messages m WHERE m.thread_id = t.id ORDER BY seq DESC LIMIT 1) AS last+ FROM account_chat_threads t WHERE t.account_id = ?${o.mature ? "" : " AND t.mature = 0"}${q ? " AND instr(lower(t.title), ?) > 0" : ""}+ ORDER BY t.updated_at DESC LIMIT ?`,+ )+ .all(...[who, ...(q ? [q] : []), Math.min(o.limit ?? 200, CHAT_LIMITS.threads)]) as (ThreadRow & { last: string | null })[];+ return rows.map((r) => summaryOf(who, r, r.last ?? ""));+}++function threadRow(who: string, id: string): ThreadRow | null {+ return (db().prepare("SELECT * FROM account_chat_threads WHERE id = ? AND account_id = ?").get(id, who) as ThreadRow | undefined) ?? null;+}++export function getThread(who: string, id: string): ChatThreadView | null {+ const r = threadRow(who, id);+ if (!r) return null;+ const messages = (db().prepare("SELECT * FROM account_chat_messages WHERE thread_id = ? AND account_id = ? ORDER BY seq").all(id, who) as MessageRow[]).map(fromMessageRow);+ return { ...summaryOf(who, r, messages.at(-1)?.content), messages, characterCard: getCharacter(who, r.character_id), shareToken: r.share_token };+}++/** What a reply needs that the browser doesn't: the summary and how far it reaches. */+export function threadMemory(who: string, id: string): { summary: string | null; upto: number } | null {+ const r = threadRow(who, id);+ return r ? { summary: r.summary, upto: r.summary_upto } : null;+}++export interface NewThread {+ kind: ChatKind;+ characterId?: string | null;+ tool?: string | null;+ play?: string | null;+ mature: boolean;+ title?: string | null;+}++export function createThread(who: string, t: NewThread): ChatThreadView {+ const n = (db().prepare("SELECT COUNT(*) AS n FROM account_chat_threads WHERE account_id = ?").get(who) as { n: number }).n;+ if (n >= CHAT_LIMITS.threads) throw new ChatError(`You have ${CHAT_LIMITS.threads} chats, the most there can be. Delete some old ones to start another.`, 409);+ const character = t.kind === "character" ? getCharacter(who, t.characterId) : null;+ if (t.kind === "character" && !character) throw new ChatError("Pick a character to chat with.", 404);+ if (character?.mature && !t.mature) throw new ChatError("Turn on Mango Chilli mode to chat with this character.", 403, "mature-off");+ const tool = t.kind === "write" ? (writeTool(t.tool)?.id ?? null) : null;+ const play = t.kind === "play" ? (playFormat(t.play)?.id ?? null) : null;+ const id = newId("ct");+ const now = Date.now();+ const title = clip(t.title, CHAT_LIMITS.titleChars) || (character ? character.name : tool ? writeTool(tool)!.name : play ? playFormat(play)!.name : "New chat");+ const d = db();+ d.transaction(() => {+ d.prepare("INSERT INTO account_chat_threads (id, account_id, kind, title, character_id, tool, play, mature, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(+ id,+ who,+ t.kind,+ title,+ character?.id ?? null,+ tool,+ play,+ // A chat started while Mango Chilli is on with a mature character stays out of the list when it's off.+ character?.mature ? 1 : 0,+ now,+ now,+ );+ if (character) d.prepare("INSERT INTO account_chat_messages (id, thread_id, account_id, seq, role, content, created_at) VALUES (?, ?, ?, 1, 'assistant', ?, ?)").run(newId("cm"), id, who, character.greeting, now);+ })();+ return getThread(who, id)!;+}++export function addMessage(who: string, threadId: string, role: "user" | "assistant", content: string, image: string | null = null): ChatMessage {+ const d = db();+ return d.transaction(() => {+ const r = threadRow(who, threadId);+ if (!r) throw new ChatError("That chat is gone.", 404);+ const last = d.prepare("SELECT MAX(seq) AS s, COUNT(*) AS n FROM account_chat_messages WHERE thread_id = ?").get(threadId) as { s: number | null; n: number };+ if (last.n >= CHAT_LIMITS.messagesPerThread) throw new ChatError("This chat is as long as a chat can be. Start a new one to keep going.", 409, "too-long");+ const now = Date.now();+ const row: MessageRow = { id: newId("cm"), thread_id: threadId, account_id: who, seq: (last.s ?? 0) + 1, role, content, image_url: image, created_at: now };+ d.prepare("INSERT INTO account_chat_messages (id, thread_id, account_id, seq, role, content, image_url, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)").run(+ row.id,+ row.thread_id,+ who,+ row.seq,+ role,+ content,+ image,+ now,+ );+ // The first thing the person says names an open chat.+ const title = role === "user" && r.title === "New chat" ? titleFrom(content) : r.title;+ d.prepare("UPDATE account_chat_threads SET updated_at = ?, title = ? WHERE id = ?").run(now, title, threadId);+ return fromMessageRow(row);+ })();+}++/** The turns of a chat, oldest first (for the model). */+export function threadTurns(who: string, threadId: string): (ChatMessage & { seq: number })[] {+ return (db().prepare("SELECT * FROM account_chat_messages WHERE thread_id = ? AND account_id = ? ORDER BY seq").all(threadId, who) as MessageRow[]).map((r) => ({ ...fromMessageRow(r), seq: r.seq }));+}++/** Take back the last reply (Try again), so the turn before it is answered again. True when there was one. */+export function dropLastReply(who: string, threadId: string): boolean {+ const last = db().prepare("SELECT id, role, seq FROM account_chat_messages WHERE thread_id = ? AND account_id = ? ORDER BY seq DESC LIMIT 1").get(threadId, who) as+ | { id: string; role: string; seq: number }+ | undefined;+ // A character's greeting is the chat's first line, not a reply to take back.+ if (!last || last.role !== "assistant" || last.seq === 1) return false;+ db().prepare("DELETE FROM account_chat_messages WHERE id = ?").run(last.id);+ return true;+}++/** Change their last message: it and everything after it go, and the new words take its place. */+export function rewindTo(who: string, threadId: string, messageId: string): boolean {+ const m = db().prepare("SELECT seq, role FROM account_chat_messages WHERE id = ? AND thread_id = ? AND account_id = ?").get(messageId, threadId, who) as { seq: number; role: string } | undefined;+ if (!m || m.role !== "user") return false;+ db().prepare("DELETE FROM account_chat_messages WHERE thread_id = ? AND account_id = ? AND seq >= ?").run(threadId, who, m.seq);+ // A summary that covered what's gone is rebuilt later.+ db().prepare("UPDATE account_chat_threads SET summary = CASE WHEN summary_upto >= ? THEN NULL ELSE summary END, summary_upto = CASE WHEN summary_upto >= ? THEN 0 ELSE summary_upto END WHERE id = ?").run(m.seq, m.seq, threadId);+ return true;+}++export function setSummary(who: string, threadId: string, summary: string, upto: number): void {+ db().prepare("UPDATE account_chat_threads SET summary = ?, summary_upto = ? WHERE id = ? AND account_id = ?").run(summary.slice(0, 2000), upto, threadId, who);+}++export function renameThread(who: string, id: string, title: unknown): ChatThreadSummary {+ const t = clip(title, CHAT_LIMITS.titleChars);+ if (!t) throw new ChatError("Give the chat a name.");+ if (db().prepare("UPDATE account_chat_threads SET title = ? WHERE id = ? AND account_id = ?").run(t, id, who).changes !== 1) throw new ChatError("That chat is gone.", 404);+ return getThread(who, id)!;+}++/** Delete a chat, its messages and its share link. */+export function deleteThread(who: string, id: string): boolean {+ const d = db();+ return d.transaction(() => {+ const gone = d.prepare("DELETE FROM account_chat_threads WHERE id = ? AND account_id = ?").run(id, who).changes === 1;+ if (gone) {+ d.prepare("DELETE FROM account_chat_messages WHERE thread_id = ? AND account_id = ?").run(id, who);+ d.prepare("DELETE FROM account_chat_shares WHERE thread_id = ? AND account_id = ?").run(id, who);+ }+ return gone;+ })();+}++// ---------------------------------------------------------------------------+// Settings++interface PrefsRow {+ account_id: string;+ mature_at: number | null;+ engine: string;+ key_sealed: string | null;+ key_last4: string | null;+ key_model: string | null;+ updated_at: number;+}++export interface ChatPrefs {+ mature: boolean;+ engine: ChatEngine;+ key: { last4: string; model: string } | null;+}++/** The model their own key uses when they don't pick one: a strong free model on OpenRouter. */+export const DEFAULT_KEY_MODEL = "google/gemma-4-31b-it:free";++const keyContext = (who: string) => `fuobe:chat-key:v1:${who}:openrouter`;++function prefsRow(who: string): PrefsRow | null {+ return (db().prepare("SELECT * FROM account_chat_prefs WHERE account_id = ?").get(who) as PrefsRow | undefined) ?? null;+}++export function getPrefs(who: string): ChatPrefs {+ const r = prefsRow(who);+ const key = r?.key_sealed && r.key_last4 ? { last4: r.key_last4, model: r.key_model || DEFAULT_KEY_MODEL } : null;+ return { mature: !!r?.mature_at, engine: key && r?.engine === "key" ? "key" : "site", key };+}++function upsertPrefs(who: string, set: Partial<Omit<PrefsRow, "account_id" | "updated_at">>): void {+ const before = prefsRow(who);+ const next = { mature_at: null, engine: "site", key_sealed: null, key_last4: null, key_model: null, ...before, ...set };+ db()+ .prepare(+ `INSERT INTO account_chat_prefs (account_id, mature_at, engine, key_sealed, key_last4, key_model, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)+ ON CONFLICT(account_id) DO UPDATE SET mature_at = excluded.mature_at, engine = excluded.engine, key_sealed = excluded.key_sealed, key_last4 = excluded.key_last4, key_model = excluded.key_model, updated_at = excluded.updated_at`,+ )+ .run(who, next.mature_at, next.engine, next.key_sealed, next.key_last4, next.key_model, Date.now());+}++/** Mango Chilli mode on (the person said they're 18 or older) or off. */+export function setMature(who: string, on: boolean): ChatPrefs {+ upsertPrefs(who, { mature_at: on ? Date.now() : null });+ return getPrefs(who);+}++export function setEngine(who: string, engine: ChatEngine): ChatPrefs {+ if (engine === "key" && !getPrefs(who).key) throw new ChatError("Add your OpenRouter key first.", 409);+ upsertPrefs(who, { engine });+ return getPrefs(who);+}++export function saveChatKey(who: string, key: string, model: string | null): ChatPrefs {+ upsertPrefs(who, { key_sealed: seal(key, keyContext(who)), key_last4: key.slice(-4), key_model: model, engine: "key" });+ return getPrefs(who);+}++export function setKeyModel(who: string, model: string): ChatPrefs {+ if (!getPrefs(who).key) throw new ChatError("Add your OpenRouter key first.", 409);+ upsertPrefs(who, { key_model: model });+ return getPrefs(who);+}++export function removeChatKey(who: string): ChatPrefs {+ upsertPrefs(who, { key_sealed: null, key_last4: null, key_model: null, engine: "site" });+ return getPrefs(who);+}++/** Their key, opened (null: none, or this server can't open it any more). Never sent to the browser. */+export function chatKey(who: string): { key: string; model: string } | null {+ const r = prefsRow(who);+ if (!r?.key_sealed) return null;+ const key = openSealed(r.key_sealed, keyContext(who));+ return key ? { key, model: r.key_model || DEFAULT_KEY_MODEL } : null;+}++// ---------------------------------------------------------------------------+// Shares++interface ShareRow {+ token: string;+ account_id: string;+ thread_id: string;+ mature: number;+ snapshot_json: string;+ portrait_url: string | null;+ views: number;+ created_at: number;+}++export const CHAT_SHARE_TOKEN = /^[A-Za-z0-9_-]{32}$/;++/**+ * Share a chat: a copy of its words as they are now (the last `count` messages, or the chosen ones), at a new public+ * link. Sharing again replaces the copy and the link. Pictures people sent aren't in it; a character's portrait is.+ */+export function shareThread(who: string, threadId: string, o: { messageIds?: string[] | null; count?: number } = {}): { token: string; snapshot: ChatShareSnapshot } {+ const t = getThread(who, threadId);+ if (!t) throw new ChatError("That chat is gone.", 404);+ const chosen = o.messageIds?.length ? t.messages.filter((m) => o.messageIds!.includes(m.id)) : t.messages.slice(-(o.count ?? CHAT_LIMITS.shareMessages));+ const messages = chosen.slice(-CHAT_LIMITS.shareMessages).filter((m) => m.content.trim());+ if (!messages.some((m) => m.role === "assistant")) throw new ChatError("There's nothing to share yet. Share a chat once it has a reply.", 409);+ const c = t.characterCard;+ const snapshot: ChatShareSnapshot = {+ title: t.title,+ kind: t.kind,+ mature: t.mature || !!c?.mature,+ character: c ? { id: c.id, name: c.name, tagline: c.tagline, accent: c.accent, builtIn: c.builtIn, portrait: !!c.portrait } : null,+ label: t.kind === "play" ? (playFormat(t.play)?.name ?? null) : t.kind === "write" ? (writeTool(t.tool)?.name ?? null) : null,+ messages: messages.map((m) => ({ role: m.role, content: m.content.slice(0, CHAT_LIMITS.messageChars) })),+ createdAt: Date.now(),+ };+ const token = crypto.randomBytes(24).toString("base64url");+ const d = db();+ d.transaction(() => {+ d.prepare("DELETE FROM account_chat_shares WHERE thread_id = ? AND account_id = ?").run(threadId, who);+ d.prepare("INSERT INTO account_chat_shares (token, account_id, thread_id, mature, snapshot_json, portrait_url, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)").run(+ token,+ who,+ threadId,+ snapshot.mature ? 1 : 0,+ JSON.stringify(snapshot),+ c?.portrait ?? null,+ snapshot.createdAt,+ );+ d.prepare("UPDATE account_chat_threads SET share_token = ? WHERE id = ? AND account_id = ?").run(token, threadId, who);+ })();+ return { token, snapshot };+}++/** Stop sharing a chat: the link stops working at once. */+export function unshareThread(who: string, threadId: string): void {+ const d = db();+ d.transaction(() => {+ d.prepare("DELETE FROM account_chat_shares WHERE thread_id = ? AND account_id = ?").run(threadId, who);+ d.prepare("UPDATE account_chat_threads SET share_token = NULL WHERE id = ? AND account_id = ?").run(threadId, who);+ })();+}++export interface PublicChatShare {+ token: string;+ owner: string;+ snapshot: ChatShareSnapshot;+ portrait: string | null;+ views: number;+}++/** A shared chat by its link's token (anyone may read it), or null. */+export function findChatShare(token: string): PublicChatShare | null {+ if (!CHAT_SHARE_TOKEN.test(token)) return null;+ const r = db().prepare("SELECT * FROM account_chat_shares WHERE token = ?").get(token) as ShareRow | undefined;+ if (!r) return null;+ try {+ return { token: r.token, owner: r.account_id, snapshot: JSON.parse(r.snapshot_json) as ChatShareSnapshot, portrait: r.portrait_url, views: r.views };+ } catch {+ return null;+ }+}++export function countShareView(token: string): void {+ db().prepare("UPDATE account_chat_shares SET views = views + 1 WHERE token = ?").run(token);+}++// ---------------------------------------------------------------------------++/** Everything chat-related of a deleted account (account-sweep.ts purgeAccount). */+export function deleteAccountChat(who: string): void {+ const d = db();+ d.transaction(() => {+ for (const t of ["account_chat_messages", "account_chat_threads", "account_chat_characters", "account_chat_prefs", "account_chat_shares"]) d.prepare(`DELETE FROM ${t} WHERE account_id = ?`).run(who);+ })();+}diff --git a/src/server/db.ts b/src/server/db.tsindex 1dd6237f..0bc4fc7c 100644--- a/src/server/db.ts+++ b/src/server/db.ts@@ -1209,6 +1209,8 @@ function open(): Database.Database {db.exec(SKILL_TABLES);// An account's own canvases (account-canvas.ts): not a numbered migration, so branches never clash over its place.db.exec(ACCOUNT_CANVAS_TABLES);+ // Fuobe Chat (src/server/chat/store.ts): not a numbered migration either.+ db.exec(CHAT_TABLES);// Where an account's runs go, as it picked (run-on.ts): read only while hosted runs are on, empty otherwise.db.exec(RUN_ON_TABLES);// Runs on this install's GPUs waiting to enter the line (pool-holds.ts): empty unless hosted runs are on.@@ -1249,6 +1251,73 @@ const ACCOUNT_CANVAS_TABLES = `CREATE TABLE IF NOT EXISTS account_canvases ();CREATE INDEX IF NOT EXISTS account_canvases_account ON account_canvases(account_id, updated_at DESC);`;+/**+ * Fuobe Chat (src/server/chat/store.ts): chats, their messages, the characters people make, their chat settings and the+ * public copies of shared chats. `account_id` is an account's id, or "owner" for the owner's own chats.+ */+const CHAT_TABLES = `CREATE TABLE IF NOT EXISTS account_chat_threads (+ id TEXT PRIMARY KEY,+ account_id TEXT NOT NULL,+ kind TEXT NOT NULL,+ title TEXT NOT NULL,+ character_id TEXT,+ tool TEXT,+ play TEXT,+ mature INTEGER NOT NULL DEFAULT 0,+ summary TEXT,+ summary_upto INTEGER NOT NULL DEFAULT 0,+ share_token TEXT,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL+ );+ CREATE INDEX IF NOT EXISTS account_chat_threads_account ON account_chat_threads(account_id, updated_at DESC);+ CREATE TABLE IF NOT EXISTS account_chat_messages (+ id TEXT PRIMARY KEY,+ thread_id TEXT NOT NULL,+ account_id TEXT NOT NULL,+ seq INTEGER NOT NULL,+ role TEXT NOT NULL CHECK (role IN ('user', 'assistant')),+ content TEXT NOT NULL,+ image_url TEXT,+ created_at INTEGER NOT NULL+ );+ CREATE INDEX IF NOT EXISTS account_chat_messages_thread ON account_chat_messages(thread_id, seq);+ CREATE TABLE IF NOT EXISTS account_chat_characters (+ id TEXT PRIMARY KEY,+ account_id TEXT NOT NULL,+ name TEXT NOT NULL,+ tagline TEXT NOT NULL,+ persona TEXT NOT NULL,+ scenario TEXT NOT NULL,+ greeting TEXT NOT NULL,+ mature INTEGER NOT NULL DEFAULT 0,+ accent TEXT NOT NULL,+ portrait_url TEXT,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL+ );+ CREATE INDEX IF NOT EXISTS account_chat_characters_account ON account_chat_characters(account_id, updated_at DESC);+ CREATE TABLE IF NOT EXISTS account_chat_prefs (+ account_id TEXT PRIMARY KEY,+ mature_at INTEGER,+ engine TEXT NOT NULL DEFAULT 'site',+ key_sealed TEXT,+ key_last4 TEXT,+ key_model TEXT,+ updated_at INTEGER NOT NULL+ );+ CREATE TABLE IF NOT EXISTS account_chat_shares (+ token TEXT PRIMARY KEY,+ account_id TEXT NOT NULL,+ thread_id TEXT NOT NULL,+ mature INTEGER NOT NULL DEFAULT 0,+ snapshot_json TEXT NOT NULL,+ portrait_url TEXT,+ views INTEGER NOT NULL DEFAULT 0,+ created_at INTEGER NOT NULL+ );+ CREATE INDEX IF NOT EXISTS account_chat_shares_thread ON account_chat_shares(thread_id);`;+/*** Where an account's runs go while hosted runs are on, as it picked (run-on.ts): this install's GPUs, its own GPU, or* its own key (`run_key`: which provider's). No row: the install's default. Not a numbered migration either.diff --git a/src/server/generations.ts b/src/server/generations.tsindex 247c937e..1cdfb679 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -844,6 +844,10 @@ export const ASSET_REFS: AssetRef[] = [// (skill-runs.ts STUDIO_TABLES). `account` lets a row keep only its own account's files.{ table: "account_canvases", cols: ["pages_json"], what: "account canvas", key: "id", name: "name", account: "account_id" },{ table: "account_projects", cols: ["data_json", "summary_json"], what: "account project", key: "id", name: "name", account: "account_id" },+ // Fuobe Chat: a picture sent in a chat, a character's portrait, and a shared chat's portrait.+ { table: "account_chat_messages", cols: ["image_url"], what: "chat", key: "thread_id", name: "(SELECT title FROM account_chat_threads WHERE id = thread_id)", account: "account_id" },+ { table: "account_chat_characters", cols: ["portrait_url"], what: "chat character", key: "id", name: "name", account: "account_id" },+ { table: "account_chat_shares", cols: ["portrait_url"], what: "shared chat", key: "token", name: "json_extract(snapshot_json, '$.title')", account: "account_id" },];/**@@ -915,6 +919,7 @@ export const ASSET_FREE: Record<string, string> = {"relay_workers.cpu_slot_json": "the kinds of finishing job a worker's CPU slot runs","relay_pairings.facts_json": "what a paired ComfyUI said about itself: its name, GPU and version","account_canvases.summary_json": "an account board's list line: node and page counts, and its outline (node types, places and short labels)",+ "account_chat_shares.snapshot_json": "a shared chat's words and its character's name and colours; its portrait is the row's portrait_url",};/** The query that finds the rows of one ASSET_REFS table naming a file (@id), except the purged generation's own (@g). */diff --git a/tests/chat.test.ts b/tests/chat.test.tsnew file mode 100644index 00000000..2c3cdc03--- /dev/null+++ b/tests/chat.test.ts@@ -0,0 +1,311 @@+/**+ * Fuobe Chat: its prompts (history that fits, Make it lines, titles, Mango Chilli wording), its store (each account's+ * chats, characters and settings are its own), its routes through the proxy (accounts in, guests to the sign-up card),+ * a reply from the free text helper through a stand-in slot, shares at /c/<token>, and an account's deletion.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import { NextRequest } from "next/server";+import { tempDir } from "./helpers/temp-dir";++vi.setConfig({ testTimeout: 30_000 });+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));++const dir = tempDir("fuobe-chat-");+process.env.FUOBE_DATA_DIR = dir;+process.env.COMFYUI_URL = "http://127.0.0.1:7";+process.env.FUOBE_PUBLIC_SIGNUP = "1";+process.env.FUOBE_HOSTED_RUNS = "1";+delete process.env.FUOBE_PASSWORD;+delete process.env.FUOBE_MODERATION_URL;++const prompt = await import("@/lib/chat/prompt");+const catalog = await import("@/lib/chat/catalog");+const { chatShareRoute } = await import("@/lib/chat/share");+const auth = await import("@/server/auth");+const { db } = await import("@/server/db");+const { resetRates } = await import("@/server/rate");+const pool = await import("@/server/computer/pool");+const helper = await import("@/server/text-helper");+const store = await import("@/server/chat/store");+const { purgeAccount } = await import("@/server/account-sweep");+const { proxy } = await import("@/proxy");+const threadsRoute = await import("@/app/api/chat/threads/route");+const threadRoute = await import("@/app/api/chat/threads/[id]/route");+const replyRoute = await import("@/app/api/chat/threads/[id]/reply/route");+const shareRoute = await import("@/app/api/chat/threads/[id]/share/route");+const meRoute = await import("@/app/api/chat/me/route");+const charactersRoute = await import("@/app/api/chat/characters/route");++type WorkerRow = import("@/server/computer/workers").WorkerRow;+const workerRow = (id: string) => db().prepare("SELECT * FROM relay_workers WHERE id = ?").get(id) as WorkerRow;++let a = "";+let b = "";+const cookies: Record<string, string> = {};+let worker = "";++beforeAll(() => {+ auth.setPassword("install password");+ a = auth.createAccount("[email protected]", "long enough").id;+ b = auth.createAccount("[email protected]", "long enough").id;+ cookies.a = `${auth.SESSION_COOKIE}=${auth.createSession(a).value}`;+ cookies.b = `${auth.SESSION_COOKIE}=${auth.createSession(b).value}`;+ const w = pool.addWorker("pc-chat");+ pool.patchWorker(w.id, { paused: false, hours: { always: true } });+ worker = w.id;+});+beforeEach(() => resetRates());+afterAll(() => {+ delete process.env.FUOBE_HOSTED_RUNS;+});++const beat = () =>+ pool.workerBeat(workerRow(worker), pool.cleanBeat({ device: `wkr-${worker}`, protocol: 3, version: "1", local: { paused: false, why: null, until: null }, gpu: {}, inventoryHash: null, running: [], stopped: [] }));++/** A stand-in text slot answering every job with `answer(job)` until stopped. */+function standIn(answer: (job: { system: string; user: string; task: string }) => string) {+ let on = true;+ const seen: { system: string; user: string; task: string }[] = [];+ const done = (async () => {+ while (on) {+ beat();+ const job = helper.claimHelperJob(workerRow(worker), { model: "test", device: "gpu" });+ if (job) {+ seen.push(job);+ helper.finishHelperJob(workerRow(worker), job.id, { lease: job.lease, text: answer(job) });+ } else await new Promise((r) => setTimeout(r, 20));+ }+ })();+ return {+ seen,+ stop: async () => {+ on = false;+ await done;+ },+ };+}++const req = (who: string, url: string, method = "GET", body?: unknown) =>+ new Request(`http://localhost:3000${url}`, { method, headers: { cookie: who, host: "localhost:3000", "content-type": "application/json" }, ...(body !== undefined && { body: JSON.stringify(body) }) });+const ctx = <T extends Record<string, string>>(params: T) => ({ params: Promise.resolve(params) }) as never;++async function events(res: Response) {+ const text = await res.text();+ return text+ .split("\n")+ .filter(Boolean)+ .map((l) => JSON.parse(l) as { type: string; [k: string]: unknown });+}++// ---------------------------------------------------------------------------++describe("what the model reads", () => {+ it("keeps the newest turns that fit, and always the last", () => {+ const turns = Array.from({ length: 20 }, (_, i) => ({ role: (i % 2 ? "assistant" : "user") as "user" | "assistant", content: `message ${i} ${"x".repeat(80)}` }));+ const fit = prompt.fitHistory(turns, 600);+ expect(fit.turns.at(-1)).toEqual(turns.at(-1));+ expect(fit.dropped).toBe(turns.length - fit.turns.length);+ expect(fit.turns.reduce((n, t) => n + t.content.length + 16, 0)).toBeLessThanOrEqual(600);+ // It starts on the person's turn when it cut the chat.+ expect(fit.turns[0].role).toBe("user");+ // One huge last turn is cut to the budget, not dropped.+ const big = prompt.fitHistory([{ role: "user", content: "y".repeat(5000) }], 1000);+ expect(big.turns).toHaveLength(1);+ expect(big.turns[0].content.length).toBeLessThanOrEqual(1000);+ });++ it("turns Prompt lines into Make it cards, in order", () => {+ const parts = prompt.splitMakeIts("### Linen at dusk\nA slow walk.\nPrompt (video): A model in linen walks along a pier at dusk, the camera tracking beside her\n\n### Fig\nPrompt: Midnight fig perfume bottle on black velvet, rim light\nMore words.");+ expect(parts.map((p) => p.kind)).toEqual(["text", "make", "text", "make", "text"]);+ expect(parts[1]).toMatchObject({ kind: "make", make: { studio: "video" } });+ expect(parts[3]).toMatchObject({ kind: "make", make: { studio: "image", prompt: "Midnight fig perfume bottle on black velvet, rim light" } });+ expect(prompt.makeItHref({ studio: "music", prompt: "lo-fi & rain" })).toBe("/audio/music?prompt=lo-fi%20%26%20rain");+ });++ it("names a chat from its first line, and tidies a reply", () => {+ expect(prompt.titleFrom(" Plan a shoot ")).toBe("Plan a shoot");+ expect(prompt.titleFrom("word ".repeat(30)).length).toBeLessThanOrEqual(61);+ expect(prompt.tidyReply("<think>hm</think>Sienna Vale: Ten minutes.", "Sienna Vale")).toBe("Ten minutes.");+ });++ it("says Mango Chilli only when it's on, and keeps characters adult either way", () => {+ const sienna = catalog.builtInCharacter("sienna-vale")!;+ const general = prompt.systemPrompt({ kind: "character", character: sienna, mature: false });+ const mature = prompt.systemPrompt({ kind: "character", character: sienna, mature: true });+ expect(general).toContain("You are Sienna Vale.");+ expect(general).toContain("explicit content is not");+ expect(general).not.toContain(catalog.MANGO_CHILLI.name);+ expect(mature).toContain(catalog.MANGO_CHILLI.name);+ for (const s of [general, mature]) expect(s).toContain("Every character in the story is an adult");+ expect(prompt.systemPrompt({ kind: "ideas", mature: false })).toContain("Prompt (image):");+ });++ it("every built-in character is complete, and mature ones are marked", () => {+ for (const c of catalog.BUILT_IN_CHARACTERS) {+ expect(c.name && c.persona && c.greeting && c.scenario).toBeTruthy();+ expect(c.accent.every((x) => /^#[0-9a-f]{6}$/i.test(x))).toBe(true);+ }+ expect(catalog.BUILT_IN_CHARACTERS.some((c) => c.mature)).toBe(true);+ expect(catalog.BUILT_IN_CHARACTERS.some((c) => !c.mature)).toBe(true);+ });+});++describe("the proxy", () => {+ it("lets accounts through to their chats and sends a guest's change to the sign-up card", async () => {+ const acct = await proxy(new NextRequest("http://localhost:3000/api/chat/threads", { method: "POST", headers: { cookie: cookies.a, host: "localhost:3000", origin: "http://localhost:3000" } }));+ expect(acct.headers.get("x-middleware-next")).toBe("1");+ const guest = await proxy(new NextRequest("http://localhost:3000/api/chat/threads", { method: "POST", headers: { host: "localhost:3000", origin: "http://localhost:3000" } }));+ expect(guest.status).toBe(401);+ expect(guest.headers.get("x-fuobe-guest")).toBe("1");+ });++ it("opens a shared chat's page to anyone, and nothing else under /c/", async () => {+ const token = "a".repeat(32);+ expect(chatShareRoute(`/c/${token}`)).toBe(true);+ expect(chatShareRoute(`/c/${token}/portrait`)).toBe(true);+ expect(chatShareRoute(`/c/${token}/opengraph-image`)).toBe(true);+ expect(chatShareRoute(`/c/${token}/other`)).toBe(false);+ expect(chatShareRoute("/c/short")).toBe(false);+ const open = await proxy(new NextRequest(`http://localhost:3000/c/${token}`, { headers: { host: "localhost:3000" } }));+ expect(open.headers.get("x-middleware-next")).toBe("1");+ // Only reads: a POST there is no share.+ const post = await proxy(new NextRequest(`http://localhost:3000/c/${token}`, { method: "POST", headers: { host: "localhost:3000", origin: "http://localhost:3000" } }));+ expect(post.headers.get("x-middleware-next")).not.toBe("1");+ });+});++describe("an account's chats are its own", () => {+ it("one account never reads, renames, shares or deletes another's chat", async () => {+ const r = await threadsRoute.POST(req(cookies.a, "/api/chat/threads", "POST", { kind: "chat", text: "What should I wear to a gallery opening?" }));+ expect(r.status).toBe(201);+ const t = (await r.json()) as { id: string; title: string; messages: unknown[] };+ expect(t.title).toBe("What should I wear to a gallery opening?");+ expect(t.messages).toHaveLength(1);+ expect((await threadRoute.GET(req(cookies.b, `/api/chat/threads/${t.id}`), ctx({ id: t.id }))).status).toBe(404);+ expect((await threadRoute.PATCH(req(cookies.b, `/api/chat/threads/${t.id}`, "PATCH", { title: "mine" }), ctx({ id: t.id }))).status).toBe(404);+ expect((await shareRoute.POST(req(cookies.b, `/api/chat/threads/${t.id}/share`, "POST", {}), ctx({ id: t.id }))).status).toBe(404);+ expect((await threadRoute.DELETE(req(cookies.b, `/api/chat/threads/${t.id}`, "DELETE"), ctx({ id: t.id }))).status).toBe(404);+ const listB = (await (await threadsRoute.GET(req(cookies.b, "/api/chat/threads"))).json()) as { items: unknown[] };+ expect(listB.items).toEqual([]);+ expect((await threadRoute.GET(req(cookies.a, `/api/chat/threads/${t.id}`), ctx({ id: t.id }))).status).toBe(200);+ });++ it("a guest gets the sign-up answer from the routes too", async () => {+ const r = await threadsRoute.POST(new Request("http://localhost:3000/api/chat/threads", { method: "POST", headers: { host: "localhost:3000", "content-type": "application/json" }, body: "{}" }));+ expect(r.status).toBe(401);+ expect(r.headers.get("x-fuobe-guest")).toBe("1");+ });++ it("keeps mature characters behind Mango Chilli mode, which needs an adult's yes", async () => {+ const valentina = catalog.BUILT_IN_CHARACTERS.find((c) => c.mature)!;+ const list = (await (await charactersRoute.GET(req(cookies.a, "/api/chat/characters"))).json()) as { items: { id: string }[] };+ expect(list.items.some((c) => c.id === valentina.id)).toBe(false);+ const refused = await threadsRoute.POST(req(cookies.a, "/api/chat/threads", "POST", { kind: "character", characterId: valentina.id }));+ expect(refused.status).toBe(403);+ expect((await refused.json()).code).toBe("mature-off");+ expect((await meRoute.PATCH(req(cookies.a, "/api/chat/me", "PATCH", { mature: true }))).status).toBe(400);+ const on = await meRoute.PATCH(req(cookies.a, "/api/chat/me", "PATCH", { mature: true, adult: true }));+ expect((await on.json()).mature).toBe(true);+ const t = await threadsRoute.POST(req(cookies.a, "/api/chat/threads", "POST", { kind: "character", characterId: valentina.id }));+ expect(t.status).toBe(201);+ const view = (await t.json()) as { id: string; mature: boolean; messages: { role: string; content: string }[] };+ expect(view.mature).toBe(true);+ expect(view.messages[0]).toMatchObject({ role: "assistant", content: valentina.greeting });+ // Turned off, the chat stays out of the list and out of reach.+ await meRoute.PATCH(req(cookies.a, "/api/chat/me", "PATCH", { mature: false }));+ const hidden = (await (await threadsRoute.GET(req(cookies.a, "/api/chat/threads"))).json()) as { items: { id: string }[] };+ expect(hidden.items.some((x) => x.id === view.id)).toBe(false);+ expect((await threadRoute.GET(req(cookies.a, `/api/chat/threads/${view.id}`), ctx({ id: view.id }))).status).toBe(403);+ });++ it("makes characters with checks, and keeps them per account", async () => {+ const r = await charactersRoute.POST(req(cookies.a, "/api/chat/characters", "POST", { name: "Aurelie", persona: "A perfumer in Grasse, precise and warm.", tagline: "Perfumer" }));+ expect(r.status).toBe(201);+ const c = (await r.json()) as { id: string; greeting: string };+ expect(c.greeting).toContain("Aurelie");+ expect(store.getCharacter(b, c.id)).toBeNull();+ expect((await charactersRoute.POST(req(cookies.a, "/api/chat/characters", "POST", { name: "", persona: "x" }))).status).toBe(400);+ // A portrait must be the person's own picture.+ expect((await charactersRoute.POST(req(cookies.a, "/api/chat/characters", "POST", { name: "X", persona: "Someone with a voice.", portrait: "/api/files/uploads/x.png" }))).status).toBe(400);+ });+});++describe("a reply", () => {+ it("comes from the free text helper with the chat's system prompt and history, and is saved", async () => {+ const slot = standIn((job) => (job.task === "write" && job.user.includes("Write You's next reply") ? "Try a black wool coat over a silk slip.\n\nPrompt (image): A model in a black wool coat over a champagne silk slip at a gallery opening" : "Summary."));+ try {+ const t = (await (await threadsRoute.POST(req(cookies.a, "/api/chat/threads", "POST", { kind: "chat", text: "Gallery opening outfit?" }))).json()) as { id: string };+ const res = await replyRoute.POST(req(cookies.a, `/api/chat/threads/${t.id}/reply`, "POST", {}), ctx({ id: t.id }));+ expect(res.headers.get("content-type")).toContain("application/x-ndjson");+ const ev = await events(res);+ const done = ev.find((e) => e.type === "done") as { message: { role: string; content: string } } | undefined;+ expect(done?.message.role).toBe("assistant");+ expect(done?.message.content).toContain("black wool coat");+ expect(slot.seen[0].system).toContain("You are Fuobe Chat");+ expect(slot.seen[0].user).toContain("User: Gallery opening outfit?");+ const view = store.getThread(a, t.id)!;+ expect(view.messages.map((m) => m.role)).toEqual(["user", "assistant"]);++ // A new message streams back as the person's, then the reply.+ const res2 = await replyRoute.POST(req(cookies.a, `/api/chat/threads/${t.id}/reply`, "POST", { text: "And shoes?" }), ctx({ id: t.id }));+ const ev2 = await events(res2);+ expect(ev2[0]).toMatchObject({ type: "user", message: { role: "user", content: "And shoes?" } });+ expect(ev2.at(-1)?.type).toBe("done");+ expect(store.getThread(a, t.id)!.messages).toHaveLength(4);++ // Try again replaces the last reply.+ const ev3 = await events(await replyRoute.POST(req(cookies.a, `/api/chat/threads/${t.id}/reply`, "POST", { retry: true }), ctx({ id: t.id })));+ expect(ev3.at(-1)?.type).toBe("done");+ expect(store.getThread(a, t.id)!.messages).toHaveLength(4);+ } finally {+ await slot.stop();+ }+ });++ it("says when the free model is busy, and keeps the person's message for Try again", async () => {+ db().prepare("DELETE FROM helper_slots").run();+ const t = (await (await threadsRoute.POST(req(cookies.a, "/api/chat/threads", "POST", { kind: "chat" }))).json()) as { id: string };+ const ev = await events(await replyRoute.POST(req(cookies.a, `/api/chat/threads/${t.id}/reply`, "POST", { text: "Hello?" }), ctx({ id: t.id })));+ expect(ev[0].type).toBe("user");+ expect(ev.at(-1)).toMatchObject({ type: "error" });+ expect(["busy", "no-model"]).toContain(ev.at(-1)?.code);+ expect(store.getThread(a, t.id)!.messages.map((m) => m.role)).toEqual(["user"]);+ });+});++describe("sharing", () => {+ it("shares a copy at a public link, stops sharing, and goes with the chat", async () => {+ const t = store.createThread(a, { kind: "chat", mature: false });+ store.addMessage(a, t.id, "user", "Hi");+ expect(() => store.shareThread(a, t.id)).toThrow(/nothing to share/);+ store.addMessage(a, t.id, "assistant", "Hello there.");+ const r = await shareRoute.POST(req(cookies.a, `/api/chat/threads/${t.id}/share`, "POST", {}), ctx({ id: t.id }));+ expect(r.status).toBe(201);+ const { token, path } = (await r.json()) as { token: string; path: string };+ expect(path).toBe(`/c/${token}`);+ expect(chatShareRoute(path)).toBe(true);+ // A copy: later messages aren't in it.+ store.addMessage(a, t.id, "user", "private follow-up");+ expect(store.findChatShare(token)!.snapshot.messages.map((m) => m.content)).toEqual(["Hi", "Hello there."]);+ expect((await shareRoute.DELETE(req(cookies.a, `/api/chat/threads/${t.id}/share`, "DELETE"), ctx({ id: t.id }))).status).toBe(200);+ expect(store.findChatShare(token)).toBeNull();+ const again = store.shareThread(a, t.id);+ store.deleteThread(a, t.id);+ expect(store.findChatShare(again.token)).toBeNull();+ });+});++describe("an account's deletion", () => {+ it("removes its chats, messages, characters, settings and shares", async () => {+ const t = store.createThread(b, { kind: "chat", mature: false });+ store.addMessage(b, t.id, "user", "Hi");+ store.addMessage(b, t.id, "assistant", "Hey.");+ store.shareThread(b, t.id);+ store.createCharacter(b, { name: "Bo", persona: "A friendly bookseller." });+ store.setMature(b, true);+ await purgeAccount(b);+ for (const table of ["account_chat_threads", "account_chat_messages", "account_chat_characters", "account_chat_prefs", "account_chat_shares"]) {+ expect((db().prepare(`SELECT COUNT(*) AS n FROM ${table} WHERE account_id = ?`).get(b) as { n: number }).n).toBe(0);+ }+ });+});