Skip to content

armgit / fuobe

Public Imported from GitHub
0

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.

Chat: delete or archive any chat, fold the sidebar, and cards that keep their frame on hover

Adarsh0bc7f4f1b358
diff --git a/src/app/api/chat/threads/[id]/route.ts b/src/app/api/chat/threads/[id]/route.ts
index 979c4d75..b160c4fd 100644
--- a/src/app/api/chat/threads/[id]/route.ts
+++ b/src/app/api/chat/threads/[id]/route.ts
@@ -2,7 +2,7 @@ import { connection } from "next/server";
import { z } from "zod";
import { body, chatViewer, gone, refused, signUp, tooOften } from "@/server/chat/http";
import { cancelPending } from "@/server/chat/pending";
-import { deleteThread, getPrefs, getThread, renameThread } from "@/server/chat/store";
+import { deleteThread, getPrefs, getThread, renameThread, setArchived } 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]">) {
@@ -16,8 +16,9 @@ export async function GET(request: Request, ctx: RouteContext<"/api/chat/threads
return Response.json(t);
}
-const Patch = z.object({ title: z.string().max(200) });
+const Patch = z.object({ title: z.string().max(200).optional(), archived: z.boolean().optional() });
+/** Rename a chat, or archive it (it leaves the list, kept under Archived) and bring it back. */
export async function PATCH(request: Request, ctx: RouteContext<"/api/chat/threads/[id]">) {
const v = chatViewer(request);
if (!v) return signUp();
@@ -25,9 +26,11 @@ export async function PATCH(request: Request, ctx: RouteContext<"/api/chat/threa
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 });
+ if (!p.success || (p.data.title === undefined && p.data.archived === undefined)) return Response.json({ error: "Give the chat a name." }, { status: 400 });
try {
- return Response.json(renameThread(v.who, id, p.data.title));
+ let t = p.data.title !== undefined ? renameThread(v.who, id, p.data.title) : null;
+ if (p.data.archived !== undefined) t = setArchived(v.who, id, p.data.archived);
+ return Response.json(t);
} catch (e) {
return refused(e);
}
diff --git a/src/app/api/chat/threads/route.ts b/src/app/api/chat/threads/route.ts
index 61bec978..a2e8fc76 100644
--- a/src/app/api/chat/threads/route.ts
+++ b/src/app/api/chat/threads/route.ts
@@ -10,8 +10,9 @@ 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 sp = new URL(request.url).searchParams;
+ const q = sp.get("q") ?? undefined;
+ return Response.json({ items: listThreads(v.who, { mature: getPrefs(v.who).mature, q, archived: sp.get("archived") === "1" }) });
}
const Post = z.object({
diff --git a/src/components/assist/shell.tsx b/src/components/assist/shell.tsx
index f069af3d..b75b32e8 100644
--- a/src/components/assist/shell.tsx
+++ b/src/components/assist/shell.tsx
@@ -1,9 +1,9 @@
"use client";
-import { Brain, CalendarClock, FolderPlus, MessageSquarePlus, MessagesSquare, Search, Sparkles, X } from "lucide-react";
+import { Brain, CalendarClock, ChevronRight, FolderPlus, MessageSquarePlus, MessagesSquare, PanelLeftClose, PanelLeftOpen, Search, Sparkles, X } from "lucide-react";
import Link from "next/link";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
-import { Suspense, useDeferredValue, useState } from "react";
+import { Suspense, useDeferredValue, useState, useSyncExternalStore } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Sheet, SheetContent, SheetDescription, SheetTitle } from "@/components/ui/sheet";
@@ -12,6 +12,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip
import { useHydrated, useIsGuest, useIsOwner } from "@/lib/api";
import { CharacterFace } from "@/components/chat/character-face";
import { useChatThreads } from "@/components/chat/hooks";
+import { TalkMenu } from "@/components/chat/talk-menu";
import { timeAgo } from "@/lib/format";
import { cn } from "@/lib/utils";
import { ChatMenu } from "./chat-menu";
@@ -21,30 +22,82 @@ import { ProjectDot } from "./project-dot";
/**
* Chat's workspace sidebar: New chat, Search, Skills, Memory, Scheduled, Projects and every chat (talking and making).
- * A column from xl up; below that the same list opens as a sheet from the header button.
+ * A column from lg (1024 px) up; below that the same list opens as a sheet from the header button.
*/
+/** Whether the sidebar is folded to a strip (remembered in this browser; open until the page has read it). */
+const RAIL_KEY = "fuobe:chat-rail";
+const railListeners = new Set<() => void>();
+const readFolded = () => {
+ try {
+ return window.localStorage.getItem(RAIL_KEY) === "folded";
+ } catch {
+ return false;
+ }
+};
+function setFolded(folded: boolean) {
+ try {
+ window.localStorage.setItem(RAIL_KEY, folded ? "folded" : "open");
+ } catch {
+ // Storage off (a private window): it folds for this visit only.
+ }
+ railListeners.forEach((l) => l());
+}
+const useFolded = () =>
+ useSyncExternalStore(
+ (cb) => {
+ railListeners.add(cb);
+ return () => railListeners.delete(cb);
+ },
+ readFolded,
+ () => false,
+ );
+
export function AssistShell({ children }: { children: React.ReactNode }) {
+ const folded = useFolded();
return (
<div className="flex min-w-0 flex-1">
- <aside className="sticky top-chrome hidden h-content w-64 shrink-0 flex-col border-r bg-sidebar/40 xl:flex" aria-label="Chat">
- <Suspense fallback={<RailSkeleton />}>
- <Rail />
- </Suspense>
- </aside>
+ {folded ? (
+ <aside className="sticky top-chrome hidden h-content w-14 shrink-0 flex-col items-center gap-1 border-r bg-sidebar/40 py-3 lg:flex" aria-label="Chat">
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button variant="ghost" size="icon" onClick={() => setFolded(false)} aria-label="Open the sidebar">
+ <PanelLeftOpen />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent side="right">Open the sidebar</TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button variant="ghost" size="icon" asChild aria-label="New chat">
+ <Link href="/chat">
+ <MessageSquarePlus />
+ </Link>
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent side="right">New chat</TooltipContent>
+ </Tooltip>
+ </aside>
+ ) : (
+ <aside className="sticky top-chrome hidden h-content w-64 shrink-0 flex-col border-r bg-sidebar/40 lg:flex" aria-label="Chat">
+ <Suspense fallback={<RailSkeleton />}>
+ <Rail onFold={() => setFolded(true)} />
+ </Suspense>
+ </aside>
+ )}
<div className="min-w-0 flex-1">{children}</div>
</div>
);
}
-/** The header button that opens the Assist sidebar below xl. */
+/** The header button that opens the sidebar below lg (1024 px). */
export function RailButton({ className }: { className?: string }) {
const [open, setOpen] = useState(false);
return (
<>
<Tooltip>
<TooltipTrigger asChild>
- <Button variant="ghost" size="icon-sm" className={cn("xl:hidden", className)} onClick={() => setOpen(true)} aria-label="Chats, projects, skills, memory and scheduled tasks">
+ <Button variant="ghost" size="icon-sm" className={cn("lg:hidden", className)} onClick={() => setOpen(true)} aria-label="Chats, projects, skills, memory and scheduled tasks">
<MessagesSquare />
</Button>
</TooltipTrigger>
@@ -90,7 +143,7 @@ function RailLink({ href, icon: Icon, label, active, onNavigate }: { href: strin
export { ProjectDot };
-function Rail({ onNavigate }: { onNavigate?: () => void }) {
+function Rail({ onNavigate, onFold }: { onNavigate?: () => void; onFold?: () => void }) {
const pathname = usePathname() ?? "";
const params = useSearchParams();
const router = useRouter();
@@ -115,11 +168,23 @@ function Rail({ onNavigate }: { onNavigate?: () => void }) {
return (
<div className="flex min-h-0 flex-1 flex-col">
<div className={cn("space-y-2 p-3 pb-2", onNavigate && "pt-12")}>
- <Button asChild variant="outline" className="h-9 w-full justify-start rounded-full">
- <Link href="/chat" onClick={onNavigate}>
- <MessageSquarePlus /> New chat
- </Link>
- </Button>
+ <div className="flex items-center gap-1.5">
+ <Button asChild variant="outline" className="h-9 min-w-0 flex-1 justify-start rounded-full">
+ <Link href="/chat" onClick={onNavigate}>
+ <MessageSquarePlus /> New chat
+ </Link>
+ </Button>
+ {onFold && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button variant="ghost" size="icon" className="shrink-0 text-muted-foreground" onClick={onFold} aria-label="Fold the sidebar">
+ <PanelLeftClose />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>Fold the sidebar</TooltipContent>
+ </Tooltip>
+ )}
+ </div>
<div className="relative">
<Search className="pointer-events-none absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2 text-subtle-foreground" />
<Input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search chats" aria-label="Search chats" className="h-8 rounded-lg pr-7 pl-8 text-[13px]" />
@@ -201,16 +266,20 @@ function Rail({ onNavigate }: { onNavigate?: () => void }) {
const t = row.talk;
const active = pathname === row.href;
return (
- <li key={`talk-${t.id}`}>
+ <li key={`talk-${t.id}`} className="group/chat relative">
<Link
href={row.href}
onClick={onNavigate}
aria-current={active ? "page" : undefined}
- className={cn("flex min-h-8 items-center gap-2 rounded-lg py-1.5 pr-2 pl-2.5 transition-colors hover:bg-accent", active && "bg-accent")}
+ className={cn("flex min-h-8 items-center gap-2 rounded-lg py-1.5 pr-8 pl-2.5 transition-colors hover:bg-accent", active && "bg-accent")}
>
{t.character && <CharacterFace name={t.character.name} accent={t.character.accent} portrait={t.character.portrait} className="size-5" />}
<span className="min-w-0 flex-1 truncate text-[13px]">{t.title}</span>
</Link>
+ <TalkMenu
+ chat={t}
+ className="absolute top-1/2 right-1 size-7 -translate-y-1/2 opacity-100 focus-visible:opacity-100 data-[state=open]:opacity-100 sm:opacity-0 sm:group-hover/chat:opacity-100"
+ />
</li>
);
}
@@ -246,6 +315,7 @@ function Rail({ onNavigate }: { onNavigate?: () => void }) {
<p className="px-2.5 py-2 text-[12px] text-muted-foreground">{q ? "No chats match." : "Your chats will show up here."}</p>
)}
</section>
+ {!q && <ArchivedChats enabled={hydrated && !guest} onNavigate={onNavigate} pathname={pathname} />}
</div>
<ProjectDialog
open={creating}
@@ -258,3 +328,50 @@ function Rail({ onNavigate }: { onNavigate?: () => void }) {
</div>
);
}
+
+/** The chats the person archived: folded away under the list, one tap to see them, each with its menu to bring it back. */
+function ArchivedChats({ enabled, onNavigate, pathname }: { enabled: boolean; onNavigate?: () => void; pathname: string }) {
+ const [open, setOpen] = useState(false);
+ const archived = useChatThreads(enabled, "", true);
+ const items = archived.data?.items ?? [];
+ if (!items.length) return null;
+ return (
+ <section aria-labelledby="rail-archived" className="mt-4">
+ <button
+ id="rail-archived"
+ type="button"
+ onClick={() => setOpen((o) => !o)}
+ aria-expanded={open}
+ className="flex w-full items-center gap-1.5 rounded-lg px-2.5 pt-2 pb-1 text-left text-[11px] font-medium tracking-wide text-muted-foreground uppercase hover:text-foreground"
+ >
+ <ChevronRight className={cn("size-3 transition-transform", open && "rotate-90")} />
+ Archived · {items.length}
+ </button>
+ {open && (
+ <ul className="space-y-0.5">
+ {items.map((t) => {
+ const href = `/chat/${t.id}`;
+ const active = pathname === href;
+ return (
+ <li key={t.id} className="group/chat relative">
+ <Link
+ href={href}
+ onClick={onNavigate}
+ aria-current={active ? "page" : undefined}
+ className={cn("flex min-h-8 items-center gap-2 rounded-lg py-1.5 pr-8 pl-2.5 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground", active && "bg-accent text-foreground")}
+ >
+ {t.character && <CharacterFace name={t.character.name} accent={t.character.accent} portrait={t.character.portrait} className="size-5 opacity-80" />}
+ <span className="min-w-0 flex-1 truncate text-[13px]">{t.title}</span>
+ </Link>
+ <TalkMenu
+ chat={t}
+ className="absolute top-1/2 right-1 size-7 -translate-y-1/2 opacity-100 focus-visible:opacity-100 data-[state=open]:opacity-100 sm:opacity-0 sm:group-hover/chat:opacity-100"
+ />
+ </li>
+ );
+ })}
+ </ul>
+ )}
+ </section>
+ );
+}
diff --git a/src/components/chat/chat-home.tsx b/src/components/chat/chat-home.tsx
index eae86c91..ebb722f2 100644
--- a/src/components/chat/chat-home.tsx
+++ b/src/components/chat/chat-home.tsx
@@ -322,9 +322,21 @@ function CharacterShelf({
{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">
+ {/* The card keeps its rounded frame; only the picture inside it zooms on hover. */}
+ <button
+ type="button"
+ onClick={() => onPick(c)}
+ className="relative block w-full overflow-hidden rounded-[18px] text-left [transform:translateZ(0)] focus-visible:ring-4 focus-visible:ring-brand-faint 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 rounded-none transition-transform duration-500 ease-out group-hover:scale-[1.04] motion-reduce:transition-none"
+ />
+ <span className="pointer-events-none absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/85 via-black/45 to-transparent p-3 pt-12 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" />}
diff --git a/src/components/chat/hooks.ts b/src/components/chat/hooks.ts
index 9c51fbc2..d6cb8e87 100644
--- a/src/components/chat/hooks.ts
+++ b/src/components/chat/hooks.ts
@@ -19,10 +19,14 @@ 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 = "") {
+/** The person's chats (`archived`: the ones they archived instead). */
+export function useChatThreads(enabled = true, q = "", archived = false) {
+ const sp = new URLSearchParams();
+ if (q.trim()) sp.set("q", q.trim());
+ if (archived) sp.set("archived", "1");
return useQuery({
- queryKey: ["chat", "threads", q.trim()],
- queryFn: async () => json<{ items: ChatThreadSummary[] }>(await fetch(`/api/chat/threads${q.trim() ? `?q=${encodeURIComponent(q.trim())}` : ""}`)),
+ queryKey: ["chat", "threads", q.trim(), archived],
+ queryFn: async () => json<{ items: ChatThreadSummary[] }>(await fetch(`/api/chat/threads${sp.size ? `?${sp}` : ""}`)),
staleTime: 5_000,
enabled,
});
diff --git a/src/components/chat/talk-menu.tsx b/src/components/chat/talk-menu.tsx
new file mode 100644
index 00000000..eb1072f3
--- /dev/null
+++ b/src/components/chat/talk-menu.tsx
@@ -0,0 +1,152 @@
+"use client";
+
+import { useQueryClient } from "@tanstack/react-query";
+import { Archive, ArchiveRestore, MoreHorizontal, Pencil, Trash2 } from "lucide-react";
+import { useRouter } from "next/navigation";
+import { useId, useState } from "react";
+import { toast } from "sonner";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@/components/ui/alert-dialog";
+import { Button } from "@/components/ui/button";
+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import type { ChatThreadSummary } from "@/lib/chat/types";
+import { toastError } from "@/lib/refusals";
+import { cn } from "@/lib/utils";
+import { chatSend } from "./hooks";
+
+/** A chat's menu in the sidebar and its header: rename it, archive it (or bring it back), delete it. */
+export function TalkMenu({ chat, className, align = "end" }: { chat: Pick<ChatThreadSummary, "id" | "title" | "archived">; className?: string; align?: "start" | "end" }) {
+ const qc = useQueryClient();
+ const router = useRouter();
+ const [renaming, setRenaming] = useState(false);
+ const [deleting, setDeleting] = useState(false);
+ const refresh = () => qc.invalidateQueries({ queryKey: ["chat"] });
+ const leaveIfOpen = () => {
+ if (typeof window !== "undefined" && window.location.pathname === `/chat/${chat.id}`) router.push("/chat");
+ };
+
+ const archive = async (on: boolean) => {
+ try {
+ await chatSend(`/api/chat/threads/${chat.id}`, "PATCH", { archived: on });
+ void refresh();
+ toast(on ? "Archived. Find it under Archived in the sidebar." : "Back in your chats", { duration: 2000 });
+ if (on) leaveIfOpen();
+ } catch (e) {
+ toastError(e);
+ }
+ };
+ const remove = async () => {
+ try {
+ await chatSend(`/api/chat/threads/${chat.id}`, "DELETE");
+ void refresh();
+ toast("Chat deleted", { duration: 1500 });
+ leaveIfOpen();
+ } catch (e) {
+ toastError(e);
+ }
+ };
+
+ return (
+ <>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="ghost" size="icon-sm" className={cn("text-muted-foreground", className)} aria-label={`More for ${chat.title}`}>
+ <MoreHorizontal />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align={align} className="w-48">
+ <DropdownMenuItem onSelect={() => setRenaming(true)}>
+ <Pencil /> Rename…
+ </DropdownMenuItem>
+ {chat.archived ? (
+ <DropdownMenuItem onSelect={() => void archive(false)}>
+ <ArchiveRestore /> Unarchive
+ </DropdownMenuItem>
+ ) : (
+ <DropdownMenuItem onSelect={() => void archive(true)}>
+ <Archive /> Archive
+ </DropdownMenuItem>
+ )}
+ <DropdownMenuSeparator />
+ <DropdownMenuItem variant="destructive" onSelect={() => setDeleting(true)}>
+ <Trash2 /> Delete…
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <Dialog open={renaming} onOpenChange={setRenaming}>
+ <DialogContent className="sm:max-w-[420px]">{renaming && <RenameForm chat={chat} onDone={() => setRenaming(false)} onSaved={refresh} />}</DialogContent>
+ </Dialog>
+ <AlertDialog open={deleting} onOpenChange={setDeleting}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Delete this chat?</AlertDialogTitle>
+ <AlertDialogDescription>“{chat.title}” and its messages are removed for good, and its share link stops working. Anything it made stays in your Library. To keep it out of the way instead, archive it.</AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ {!chat.archived && (
+ <Button variant="outline" onClick={() => (setDeleting(false), void archive(true))}>
+ Archive instead
+ </Button>
+ )}
+ <AlertDialogAction variant="destructive" onClick={() => void remove()}>
+ Delete
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </>
+ );
+}
+
+function RenameForm({ chat, onDone, onSaved }: { chat: Pick<ChatThreadSummary, "id" | "title">; onDone: () => void; onSaved: () => void }) {
+ const id = useId();
+ const [title, setTitle] = useState(chat.title);
+ const [busy, setBusy] = useState(false);
+ const save = async (e: React.FormEvent) => {
+ e.preventDefault();
+ const t = title.trim();
+ if (!t || t === chat.title) return onDone();
+ setBusy(true);
+ try {
+ await chatSend(`/api/chat/threads/${chat.id}`, "PATCH", { title: t });
+ onSaved();
+ onDone();
+ } catch (err) {
+ toastError(err);
+ } finally {
+ setBusy(false);
+ }
+ };
+ return (
+ <form onSubmit={save} className="space-y-4">
+ <DialogHeader>
+ <DialogTitle className="font-heading text-[24px] font-normal">Rename chat</DialogTitle>
+ <DialogDescription className="sr-only">Give this chat a new name.</DialogDescription>
+ </DialogHeader>
+ <div className="space-y-2">
+ <Label htmlFor={id}>Name</Label>
+ <Input id={id} value={title} onChange={(e) => setTitle(e.target.value)} maxLength={80} autoFocus onFocus={(e) => e.currentTarget.select()} />
+ </div>
+ <DialogFooter>
+ <Button type="button" variant="ghost" onClick={onDone}>
+ Cancel
+ </Button>
+ <Button type="submit" disabled={busy || !title.trim()}>
+ Save
+ </Button>
+ </DialogFooter>
+ </form>
+ );
+}
diff --git a/src/components/chat/thread-view.tsx b/src/components/chat/thread-view.tsx
index 271ab68e..bac737c9 100644
--- a/src/components/chat/thread-view.tsx
+++ b/src/components/chat/thread-view.tsx
@@ -1,10 +1,11 @@
"use client";
import { useQueryClient } from "@tanstack/react-query";
-import { ArrowLeft, Check, Copy, MoreHorizontal, Pencil, RotateCcw, Share2, Trash2, X } from "lucide-react";
+import { Archive, ArchiveRestore, 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, useMemo, useRef, useState } from "react";
+import { toast } from "sonner";
import { RailButton } from "@/components/assist/shell";
import { PhoneNavButton } from "@/components/nav/phone-nav-button";
import {
@@ -118,7 +119,7 @@ export function ThreadView({ id }: { id: string }) {
<Frame>
<header className="flex h-14 shrink-0 items-center gap-2 border-b px-3 sm:px-5">
<RailButton />
- <Button variant="ghost" size="icon" asChild aria-label="Chat home" className="xl:hidden">
+ <Button variant="ghost" size="icon" asChild aria-label="Chat home" className="lg:hidden">
<Link href="/chat">
<ArrowLeft />
</Link>
@@ -169,6 +170,22 @@ export function ThreadView({ id }: { id: string }) {
<DropdownMenuItem onSelect={() => setRenaming(true)}>
<Pencil /> Rename
</DropdownMenuItem>
+ <DropdownMenuItem
+ onSelect={async () => {
+ try {
+ await chatSend(`/api/chat/threads/${id}`, "PATCH", { archived: !t.archived });
+ void qc.invalidateQueries({ queryKey: ["chat"] });
+ if (!t.archived) {
+ toast("Archived. Find it under Archived in the sidebar.", { duration: 2000 });
+ router.push("/chat");
+ }
+ } catch (e) {
+ toastError(e);
+ }
+ }}
+ >
+ {t.archived ? <ArchiveRestore /> : <Archive />} {t.archived ? "Unarchive" : "Archive"}
+ </DropdownMenuItem>
<DropdownMenuItem onSelect={() => setSettings(true)}>Chat settings</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem variant="destructive" onSelect={() => setDeleting(true)}>
diff --git a/src/components/chat/workshop.tsx b/src/components/chat/workshop.tsx
index 7d5710ee..54ab4e05 100644
--- a/src/components/chat/workshop.tsx
+++ b/src/components/chat/workshop.tsx
@@ -49,7 +49,7 @@ export function WorkshopGrid({ onPick }: { onPick: (p: PlayFormat) => void }) {
key={p.id}
type="button"
onClick={() => onPick(p)}
- className="group relative block w-full overflow-hidden rounded-[18px] text-left focus-visible:ring-4 focus-visible:ring-brand-faint focus-visible:outline-none"
+ className="group relative block w-full overflow-hidden rounded-[18px] text-left [transform:translateZ(0)] focus-visible:ring-4 focus-visible:ring-brand-faint focus-visible:outline-none"
aria-label={`${p.name}: ${p.blurb}`}
>
<WorkshopCover format={p} className="aspect-[4/5] w-full transition-transform duration-500 ease-out group-hover:scale-[1.03] motion-reduce:transition-none" />
diff --git a/src/lib/chat/types.ts b/src/lib/chat/types.ts
index b07d5f1e..6131eb06 100644
--- a/src/lib/chat/types.ts
+++ b/src/lib/chat/types.ts
@@ -55,6 +55,8 @@ export interface ChatThreadSummary {
tool: string | null;
play: string | null;
mature: boolean;
+ /** Archived: out of the list, kept under Archived. */
+ archived: boolean;
/** The last message, cut short. */
preview: string;
updatedAt: number;
diff --git a/src/server/chat/store.ts b/src/server/chat/store.ts
index 92c9b7de..340bc085 100644
--- a/src/server/chat/store.ts
+++ b/src/server/chat/store.ts
@@ -158,6 +158,7 @@ interface ThreadRow {
summary: string | null;
summary_upto: number;
share_token: string | null;
+ archived_at?: number | null;
created_at: number;
updated_at: number;
}
@@ -211,6 +212,7 @@ function summaryOf(who: string, r: ThreadRow, last?: string): ChatThreadSummary
tool: r.tool,
play: r.play,
mature: !!r.mature,
+ archived: !!r.archived_at,
// Plain words for the list line: no markdown marks, no "Prompt (image):" labels.
preview: (last ?? "")
.replace(/^\s*prompt\s*(\([a-z]+\))?\s*:/gim, "")
@@ -223,12 +225,12 @@ function summaryOf(who: string, r: ThreadRow, last?: string): ChatThreadSummary
}
/** 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[] {
+export function listThreads(who: string, o: { mature: boolean; q?: string; limit?: number; archived?: boolean } = { 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" : ""}
+ FROM account_chat_threads t WHERE t.account_id = ? AND t.archived_at IS ${o.archived ? "NOT NULL" : "NULL"}${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 })[];
@@ -555,3 +557,10 @@ export function deleteAccountChat(who: string): void {
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);
})();
}
+
+/** Archive a chat (it leaves the list, kept under Archived) or bring it back. */
+export function setArchived(who: string, id: string, archived: boolean): ChatThreadSummary {
+ const r = db().prepare("UPDATE account_chat_threads SET archived_at = ? WHERE id = ? AND account_id = ?").run(archived ? Date.now() : null, id, who);
+ if (r.changes !== 1) throw new ChatError("That chat is gone.", 404);
+ return getThread(who, id)!;
+}
diff --git a/src/server/db.ts b/src/server/db.ts
index 9826af2e..291c00c1 100644
--- a/src/server/db.ts
+++ b/src/server/db.ts
@@ -1275,6 +1275,10 @@ function open(): Database.Database {
db.exec(ACCOUNT_CANVAS_TABLES);
// Fuobe Chat (src/server/chat/store.ts): not a numbered migration either.
db.exec(CHAT_TABLES);
+ // When a chat was archived (it leaves the list, kept under Archived), for tables made before it.
+ if (!(db.prepare("PRAGMA table_info(account_chat_threads)").all() as { name: string }[]).some((c) => c.name === "archived_at")) {
+ addColumn(db, "ALTER TABLE account_chat_threads ADD COLUMN archived_at INTEGER");
+ }
// A chat message's plan to make something (its runs and their inputs), for tables made before it.
if (!(db.prepare("PRAGMA table_info(account_chat_messages)").all() as { name: string }[]).some((c) => c.name === "data_json")) {
addColumn(db, "ALTER TABLE account_chat_messages ADD COLUMN data_json TEXT");
diff --git a/tests/chat.test.ts b/tests/chat.test.ts
index 3b3c0c22..b0209ce1 100644
--- a/tests/chat.test.ts
+++ b/tests/chat.test.ts
@@ -217,6 +217,21 @@ describe("an account's chats are its own", () => {
expect((await page()).status).toBe(404);
});
+ it("archives a chat out of the list and brings it back", async () => {
+ const t = store.createThread(a, { kind: "chat", title: "Archive me", mature: false });
+ const ids = async (archived: boolean) =>
+ ((await (await threadsRoute.GET(req(cookies.a, `/api/chat/threads${archived ? "?archived=1" : ""}`))).json()) as { items: { id: string; archived: boolean }[] }).items.map((x) => x.id);
+ expect(await ids(false)).toContain(t.id);
+ const r = await threadRoute.PATCH(req(cookies.a, `/api/chat/threads/${t.id}`, "PATCH", { archived: true }), ctx({ id: t.id }));
+ expect(((await r.json()) as { archived: boolean }).archived).toBe(true);
+ expect(await ids(false)).not.toContain(t.id);
+ expect(await ids(true)).toContain(t.id);
+ // Another account can't archive it.
+ expect((await threadRoute.PATCH(req(cookies.b, `/api/chat/threads/${t.id}`, "PATCH", { archived: false }), ctx({ id: t.id }))).status).toBe(404);
+ await threadRoute.PATCH(req(cookies.a, `/api/chat/threads/${t.id}`, "PATCH", { archived: false }), ctx({ id: t.id }));
+ expect(await ids(false)).toContain(t.id);
+ });
+
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);