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.

Assist UI: sidebar with projects and chats, Skills and Memory pages, project home, mode picker, / skills

Clauded563162bcdd6
diff --git a/src/app/(studio)/assist/layout.tsx b/src/app/(studio)/assist/layout.tsx
new file mode 100644
index 00000000..6bc03779
--- /dev/null
+++ b/src/app/(studio)/assist/layout.tsx
@@ -0,0 +1,6 @@
+import { AssistShell } from "@/components/assist/shell";
+
+/** Assist's own sidebar (chats, projects, skills, memory) beside every Assist page. */
+export default function AssistLayout({ children }: LayoutProps<"/assist">) {
+ return <AssistShell>{children}</AssistShell>;
+}
diff --git a/src/app/(studio)/assist/memory/page.tsx b/src/app/(studio)/assist/memory/page.tsx
new file mode 100644
index 00000000..cb060438
--- /dev/null
+++ b/src/app/(studio)/assist/memory/page.tsx
@@ -0,0 +1,8 @@
+import type { Metadata } from "next";
+import { MemoryView } from "@/components/assist/memory-view";
+
+export const metadata: Metadata = { title: "Memory" };
+
+export default function Page() {
+ return <MemoryView />;
+}
diff --git a/src/app/(studio)/assist/projects/[id]/page.tsx b/src/app/(studio)/assist/projects/[id]/page.tsx
new file mode 100644
index 00000000..cf6e69a3
--- /dev/null
+++ b/src/app/(studio)/assist/projects/[id]/page.tsx
@@ -0,0 +1,18 @@
+import type { Metadata } from "next";
+import { Suspense } from "react";
+import { ProjectView } from "@/components/assist/project-view";
+
+export const metadata: Metadata = { title: "Project" };
+
+async function Project({ params }: { params: PageProps<"/assist/projects/[id]">["params"] }) {
+ const { id } = await params;
+ return <ProjectView id={id} />;
+}
+
+export default function Page({ params }: PageProps<"/assist/projects/[id]">) {
+ return (
+ <Suspense fallback={null}>
+ <Project params={params} />
+ </Suspense>
+ );
+}
diff --git a/src/app/(studio)/assist/skills/page.tsx b/src/app/(studio)/assist/skills/page.tsx
new file mode 100644
index 00000000..b48a75af
--- /dev/null
+++ b/src/app/(studio)/assist/skills/page.tsx
@@ -0,0 +1,8 @@
+import type { Metadata } from "next";
+import { SkillsView } from "@/components/assist/skills-view";
+
+export const metadata: Metadata = { title: "Skills" };
+
+export default function Page() {
+ return <SkillsView />;
+}
diff --git a/src/components/assist-view.tsx b/src/components/assist-view.tsx
index 863d8d36..7b0e18a9 100644
--- a/src/components/assist-view.tsx
+++ b/src/components/assist-view.tsx
@@ -1,23 +1,25 @@
"use client";
-import { ArrowUp, AudioLines, Bot, Box, Check, CircleAlert, Clapperboard, Cpu, FileText, History, ImageIcon, Loader2, Paperclip, Plus, Search, Sparkles, Trash2, Video, X } from "lucide-react";
+import { Bot, Cpu, Loader2, MessageSquarePlus } from "lucide-react";
import Link from "next/link";
-import { usePathname, useRouter, useSearchParams } from "next/navigation";
+import { useRouter, useSearchParams } from "next/navigation";
import { useEffect, useMemo, useRef, useState } from "react";
-import { nanoid } from "nanoid";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
-import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { SidebarTrigger } from "@/components/ui/sidebar";
import { Switch } from "@/components/ui/switch";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { EngineSwitch } from "@/components/studio/engine-switch";
-import { FailedTile, MediaThumb, PendingTile, tileRatio } from "@/components/studio/feed";
import { Viewer } from "@/components/studio/viewer";
-import { uploadFile, useAssistActions, useAssistThread, useAssistThreads, useCreateGeneration, useEngine } from "@/lib/api";
-import type { AssistItem, AssistThread, PlannedJob } from "@/lib/assist";
-import { OPERATION_LABELS, type Generation, type MediaKind } from "@/lib/catalog/types";
-import { formatCost, timeAgo } from "@/lib/format";
+import { AssistComposer } from "@/components/assist/composer";
+import { useChatActions, useChats, useProjects, useSkills } from "@/components/assist/hooks";
+import { ModePicker, useModeChoice } from "@/components/assist/mode-picker";
+import { ProjectDot, RailButton } from "@/components/assist/shell";
+import { SkillIcon } from "@/components/assist/skill-icon";
+import { Transcript } from "@/components/assist/transcript";
+import { useAssistActions, useAssistThread, useEngine } from "@/lib/api";
+import { modeLabel, type AssistAvailability, type AssistModeChoice, type AssistProject, type AssistThread, type SkillSummary } from "@/lib/assist";
+import type { Generation } from "@/lib/catalog/types";
import { cn } from "@/lib/utils";
const SUGGESTIONS = [
@@ -27,434 +29,87 @@ const SUGGESTIONS = [
"A 10-second vertical video of a fox running through snow, with sound",
];
-const KIND_ICON: Record<MediaKind | "storyboard", typeof ImageIcon> = { image: ImageIcon, video: Video, audio: AudioLines, text: FileText, model3d: Box, storyboard: Clapperboard };
+/** Skills offered as one-tap starters on the empty page (Supercomputer's suggestion cards). */
+const STARTER_SKILLS = ["product-photoshoot", "ugc-video", "thumbnail-generation", "faceless-video", "short-film", "localization"];
-const AGENT_LABEL: Record<AssistThread["agent"], string> = { claude: "Claude", ollama: "Local LLM", offline: "Offline planner" };
const AGENT_HINT: Record<AssistThread["agent"], string> = {
claude: "Claude plans the shoot, picks models and runs them with your approval.",
- ollama: "Runs on your Ollama model (Settings → Prompt enhancement). Smaller local models follow instructions less reliably than Claude.",
+ ollama: "Runs on your local model through Ollama. Smaller local models follow instructions less reliably than Claude.",
offline: "A simple rule-based planner. Add an Anthropic API key, or run Ollama, for the full assistant that picks models, chains steps and checks results.",
};
-interface Attachment {
- id: string;
- preview: string;
- url?: string;
- kind: MediaKind;
-}
-
-// ---------------------------------------------------------------------------
-// Composer
-
-function Composer({
- onSend,
- disabled,
- placeholder,
- autoFocus,
- footer,
-}: {
- onSend: (text: string, attachments: string[]) => Promise<void>;
- disabled?: boolean;
- placeholder: string;
- autoFocus?: boolean;
- footer?: React.ReactNode;
-}) {
- const [text, setText] = useState("");
- const [files, setFiles] = useState<Attachment[]>([]);
- const [sending, setSending] = useState(false);
- const input = useRef<HTMLInputElement>(null);
- const uploading = files.some((f) => !f.url);
- const ready = text.trim().length > 0 && !uploading && !sending && !disabled;
-
- // Local previews (object URLs) are released once the upload settles, when removed, and on unmount.
- const blobs = useRef(new Set<string>());
- const release = (url: string) => {
- if (blobs.current.delete(url)) URL.revokeObjectURL(url);
- };
- useEffect(() => {
- const live = blobs.current;
- return () => {
- live.forEach((u) => URL.revokeObjectURL(u));
- live.clear();
- };
- }, []);
-
- const add = (list: FileList | null) => {
- for (const f of Array.from(list ?? []).slice(0, 8 - files.length)) {
- const id = nanoid(6);
- const kind: MediaKind = f.type.startsWith("video") ? "video" : f.type.startsWith("audio") ? "audio" : "image";
- const blob = URL.createObjectURL(f);
- blobs.current.add(blob);
- setFiles((xs) => [...xs, { id, kind, preview: blob }]);
- uploadFile(f)
- // Show the uploaded file, then let the blob go (after the element has switched over).
- .then((a) => {
- setFiles((xs) => xs.map((x) => (x.id === id ? { ...x, url: a.url, preview: a.url } : x)));
- setTimeout(() => release(blob), 1500);
- })
- .catch((e) => {
- toast.error((e as Error).message);
- setFiles((xs) => xs.filter((x) => x.id !== id));
- release(blob);
- });
- }
- };
- const remove = (f: Attachment) => {
- setFiles((xs) => xs.filter((x) => x.id !== f.id));
- if (f.preview.startsWith("blob:")) release(f.preview);
- };
-
- const send = async () => {
- if (!ready) return;
- setSending(true);
- try {
- await onSend(text.trim(), files.map((f) => f.url!));
- setText("");
- setFiles([]);
- } catch (e) {
- toast.error((e as Error).message);
- } finally {
- setSending(false);
- }
- };
-
- return (
- <div
- className="rounded-composer border bg-background p-2.5 shadow-soft transition focus-within:border-primary focus-within:ring-4 focus-within:ring-brand-faint"
- onDragOver={(e) => e.preventDefault()}
- onDrop={(e) => {
- e.preventDefault();
- add(e.dataTransfer.files);
- }}
- >
- {files.length > 0 && (
- <div className="mb-2 flex flex-wrap gap-2 px-1 pt-1">
- {files.map((f) => (
- <div key={f.id} className="relative size-14 overflow-hidden rounded-lg border bg-muted">
- {f.kind === "image" ? (
- // eslint-disable-next-line @next/next/no-img-element
- <img src={f.preview} alt="" className="size-full object-cover" />
- ) : f.kind === "video" ? (
- <video src={f.preview} muted className="size-full object-cover" />
- ) : (
- <AudioLines className="m-auto mt-4 size-5 text-muted-foreground" />
- )}
- {!f.url && <Loader2 className="absolute inset-0 m-auto size-4 animate-spin text-foreground" />}
- <button
- onClick={() => remove(f)}
- className="absolute top-0.5 right-0.5 grid size-4 place-items-center rounded-full bg-foreground/80 text-background"
- aria-label="Remove attachment"
- >
- <X className="size-2.5" />
- </button>
- </div>
- ))}
- </div>
- )}
- <textarea
- value={text}
- autoFocus={autoFocus}
- onChange={(e) => setText(e.target.value)}
- onPaste={(e) => e.clipboardData.files.length && add(e.clipboardData.files)}
- onKeyDown={(e) => {
- if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) {
- e.preventDefault();
- void send();
- }
- }}
- rows={1}
- placeholder={placeholder}
- className="field-sizing-content max-h-56 min-h-12 w-full resize-none bg-transparent px-2 py-1.5 text-base leading-relaxed outline-none placeholder:text-subtle-foreground"
- />
- <div className="mt-1 flex items-center gap-2">
- <input ref={input} type="file" accept="image/*,video/*,audio/*" multiple hidden onChange={(e) => (add(e.target.files), (e.target.value = ""))} />
- <Tooltip>
- <TooltipTrigger asChild>
- <button onClick={() => input.current?.click()} className="grid size-9 place-items-center rounded-full text-muted-foreground hover:bg-accent hover:text-foreground" aria-label="Attach files">
- <Paperclip className="size-4" />
- </button>
- </TooltipTrigger>
- <TooltipContent>Attach photos, video or audio</TooltipContent>
- </Tooltip>
- {footer}
- <Button size="icon" className="ml-auto size-10 rounded-full" disabled={!ready} onClick={() => void send()} aria-label="Send">
- {sending ? <Loader2 className="animate-spin" /> : <ArrowUp />}
- </Button>
- </div>
- </div>
- );
-}
-
-function AskFirst({ checked, onChange }: { checked: boolean; onChange: (v: boolean) => void }) {
+export function AskFirst({ checked, onChange }: { checked: boolean; onChange: (v: boolean) => void }) {
return (
<Tooltip>
<TooltipTrigger asChild>
- <label className="inline-flex h-9 cursor-pointer items-center gap-2 rounded-full px-2.5 text-[13px] font-medium text-muted-foreground hover:bg-accent hover:text-foreground">
+ <label className="inline-flex h-9 shrink-0 cursor-pointer items-center gap-2 rounded-full px-2.5 text-[13px] font-medium whitespace-nowrap text-muted-foreground hover:bg-accent hover:text-foreground">
<Switch size="sm" checked={checked} onCheckedChange={onChange} aria-label="Ask before generating" />
Ask first
</label>
</TooltipTrigger>
- <TooltipContent>{checked ? "You approve each plan and its cost before anything runs" : "Plans run right away — no approval card"}</TooltipContent>
+ <TooltipContent>{checked ? "You approve each plan (and each memory) before anything runs" : "Plans run right away — no approval card"}</TooltipContent>
</Tooltip>
);
}
-// ---------------------------------------------------------------------------
-// Transcript items
-
-/** Paragraphs, "- " bullets and **bold** — the little markdown the assistant uses. */
-function Prose({ text }: { text: string }) {
- const inline = (s: string) => s.split(/(\*\*[^*]+\*\*)/g).map((p, i) => (p.startsWith("**") && p.endsWith("**") ? <strong key={i}>{p.slice(2, -2)}</strong> : p));
- return (
- <div className="space-y-2.5 text-[15px] leading-relaxed">
- {text.split(/\n{2,}/).map((para, i) => {
- const lines = para.split("\n");
- if (lines.every((l) => /^\s*([-*•]|\d+\.)\s/.test(l))) {
- return (
- <ul key={i} className="list-disc space-y-1 pl-5 marker:text-muted-foreground">
- {lines.map((l, j) => (
- <li key={j}>{inline(l.replace(/^\s*([-*•]|\d+\.)\s/, ""))}</li>
- ))}
- </ul>
- );
- }
- return (
- <p key={i} className="whitespace-pre-wrap">
- {inline(para)}
- </p>
- );
- })}
- </div>
- );
-}
-
-function jobPrice(j: PlannedJob): string {
- if (j.error) return "—";
- if (j.demo) return "Demo";
- if (j.costUsd === 0) return "Free";
- return j.costUsd === null ? "Price varies" : formatCost(j.costUsd);
-}
-
-function ApprovalCard({ item, live, onAnswer }: { item: Extract<AssistItem, { role: "approval" }>; live: boolean; onAnswer: (ok: boolean) => Promise<void> }) {
- const [busy, setBusy] = useState<boolean | null>(null);
- const runnable = item.jobs.some((j) => !j.error);
- const allDemo = item.jobs.every((j) => j.demo || j.error);
- const total = allDemo ? "Demo run — no provider connected" : item.totalUsd === null ? "Some prices vary" : item.totalUsd === 0 ? "Free" : `≈ ${formatCost(item.totalUsd)}`;
- const answer = async (ok: boolean) => {
- setBusy(ok);
- try {
- await onAnswer(ok);
- } catch (e) {
- toast.error((e as Error).message);
- } finally {
- setBusy(null);
- }
- };
- return (
- <div className={cn("animate-fade-up overflow-hidden rounded-2xl border bg-background shadow-soft", item.status !== "pending" && "opacity-80")}>
- <div className="flex items-center gap-2 border-b bg-muted/40 px-4 py-2.5">
- <Sparkles className="size-3.5 text-brand-text" />
- <p className="min-w-0 flex-1 truncate text-[13px] font-medium">{item.summary}</p>
- {item.status === "approved" && (
- <span className="inline-flex items-center gap-1 text-[12px] font-medium text-brand-text">
- <Check className="size-3" /> Approved
- </span>
- )}
- {item.status === "declined" && <span className="text-[12px] text-muted-foreground">Skipped</span>}
- </div>
- <ul className="divide-y">
- {item.jobs.map((j, i) => {
- const Icon = KIND_ICON[j.op === "storyboard" ? "storyboard" : j.kind];
- return (
- <li key={i} className="flex gap-3 px-4 py-3">
- <span className="mt-0.5 grid size-8 shrink-0 place-items-center rounded-lg bg-secondary">
- <Icon className="size-4" />
- </span>
- <div className="min-w-0 flex-1">
- <p className="text-[13px] font-medium">
- {j.modelName}
- <span className="font-normal text-muted-foreground">
- {" · "}
- {j.op === "storyboard" ? `Storyboard · ${j.count} frames` : j.op === "memory" ? "Remember" : `${OPERATION_LABELS[j.op] ?? j.op}${j.count > 1 ? ` · ${j.count} takes` : ""}`}
- </span>
- </p>
- <p className="mt-0.5 line-clamp-2 text-[13px] text-muted-foreground">{j.prompt}</p>
- {j.error && (
- <p className="mt-1 flex items-center gap-1 text-[12px] text-destructive">
- <CircleAlert className="size-3" /> {j.error}
- </p>
- )}
- </div>
- <span className="shrink-0 font-mono text-[12px] text-muted-foreground">{jobPrice(j)}</span>
- </li>
- );
- })}
- </ul>
- <div className="flex flex-wrap items-center gap-2 border-t px-4 py-2.5">
- <p className="text-[12px] text-muted-foreground">{total}</p>
- {live && item.status === "pending" && (
- <div className="ml-auto flex gap-1.5">
- <Button variant="ghost" size="sm" disabled={busy !== null} onClick={() => void answer(false)}>
- Not now
- </Button>
- <Button size="sm" disabled={busy !== null || !runnable} onClick={() => void answer(true)}>
- {busy ? <Loader2 className="animate-spin" /> : <Check />} Run{item.totalUsd && !allDemo ? ` · ${formatCost(item.totalUsd)}` : ""}
- </Button>
- </div>
- )}
- </div>
- </div>
- );
-}
-
-function GenerationCards({ ids, all, storyboard, onOpen }: { ids: string[]; all: Map<string, Generation>; storyboard?: boolean; onOpen: (g: Generation, i: number) => void }) {
- const create = useCreateGeneration();
- const gens = ids.map((id) => all.get(id)).filter((g): g is Generation => !!g);
- if (!gens.length) return null;
- const tiles = gens.flatMap((g) => {
- const ratio = tileRatio(g);
- if (g.status === "succeeded") {
- return g.outputs.map((o, i) => (
- <button key={`${g.id}-${i}`} onClick={() => onOpen(g, i)} className="group relative overflow-hidden rounded-xl bg-muted" style={{ aspectRatio: ratio }}>
- <MediaThumb output={o} className="transition duration-300 group-hover:scale-[1.02]" />
- {g.provider === "mock" && <span className="absolute top-2 left-2 rounded-full bg-background/80 px-2 py-0.5 text-[10px] font-medium">Demo</span>}
- </button>
- ));
- }
- if (g.status === "failed" || g.status === "canceled") {
- return [<FailedTile key={g.id} g={g} ratio={ratio} onRetry={() => create.mutate(g.request, { onError: (e) => toast.error((e as Error).message) })} />];
- }
- return Array.from({ length: Math.max(1, g.request.params?.numOutputs ?? 1) }, (_, i) => <PendingTile key={`${g.id}-${i}`} g={g} ratio={ratio} />);
- });
- const portrait = tileRatio(gens[0]) < 1;
- return (
- <div className={cn("grid gap-2", storyboard ? "grid-cols-2 sm:grid-cols-4" : portrait ? "grid-cols-2 sm:grid-cols-3" : tiles.length === 1 ? "grid-cols-1 sm:w-4/5" : "grid-cols-2")}>
- {tiles}
- </div>
- );
+/** Usable skills for a chat: the project's own list when it has one, else every enabled skill. */
+export function chatSkills(all: SkillSummary[] | undefined, project?: AssistProject | null): SkillSummary[] {
+ if (!all) return [];
+ if (project?.skills.length) return all.filter((s) => project.skills.includes(s.name));
+ return all.filter((s) => s.enabled);
}
-function Transcript({ thread, all, onAnswer, onOpen }: { thread: AssistThread; all: Map<string, Generation>; onAnswer: (ok: boolean) => Promise<void>; onOpen: (g: Generation, i: number) => void }) {
- const lastApproval = thread.items.findLast((i) => i.role === "approval")?.id;
- return (
- <div className="space-y-5">
- {thread.items.map((item) => {
- switch (item.role) {
- case "user":
- return (
- <div key={item.id} className="flex animate-fade-up flex-col items-end gap-2">
- {item.attachments?.length ? (
- <div className="flex flex-wrap justify-end gap-1.5">
- {item.attachments.map((a) => (
- <div key={a} className="size-16 overflow-hidden rounded-xl border bg-muted">
- <MediaThumb output={{ url: a, kind: /\.(mp4|webm|mov)$/i.test(a) ? "video" : /\.(mp3|wav|ogg|m4a)$/i.test(a) ? "audio" : "image" }} />
- </div>
- ))}
- </div>
- ) : null}
- <div className="max-w-[85%] rounded-2xl rounded-br-md bg-secondary px-4 py-2.5 text-[15px] leading-relaxed whitespace-pre-wrap">{item.text}</div>
- </div>
- );
- case "assistant":
- return (
- <div key={item.id} className="animate-fade-up">
- <Prose text={item.text} />
- </div>
- );
- case "tool":
- return (
- <p key={item.id} className="flex items-center gap-1.5 text-[12px] text-muted-foreground">
- <Search className="size-3" /> {item.text}
- </p>
- );
- case "approval":
- return <ApprovalCard key={item.id} item={item} live={item.id === lastApproval && thread.status === "waiting"} onAnswer={onAnswer} />;
- case "generations":
- return <GenerationCards key={item.id} ids={item.ids} all={all} storyboard={item.storyboard} onOpen={onOpen} />;
- case "notice":
- return (
- <p
- key={item.id}
- className={cn("flex items-start gap-2 rounded-xl px-3 py-2 text-[13px]", item.tone === "error" ? "bg-destructive/10 text-destructive" : "bg-muted text-muted-foreground")}
- >
- <CircleAlert className="mt-0.5 size-3.5 shrink-0" /> {item.text}
- </p>
- );
- }
- })}
- {thread.status === "running" && (
- <p className="shimmer-text animate-shimmer-text flex items-center gap-2 text-[14px] font-medium">
- <Sparkles className="size-3.5" /> Thinking…
- </p>
- )}
- </div>
- );
-}
-
-// ---------------------------------------------------------------------------
-
-function HistoryButton({ current, onPick }: { current: string | null; onPick: (id: string | null) => void }) {
- const threads = useAssistThreads();
- const actions = useAssistActions();
- const [open, setOpen] = useState(false);
+/** The composer's chips for a new chat: mode, engine, ask-first. */
+export function NewChatControls({
+ choice,
+ setChoice,
+ can,
+ engine,
+ setEngine,
+ askFirst,
+ setAskFirst,
+}: {
+ choice: AssistModeChoice | null;
+ setChoice: (c: AssistModeChoice) => void;
+ can?: AssistAvailability;
+ engine: "cloud" | "open";
+ setEngine: (e: "cloud" | "open") => void;
+ askFirst: boolean;
+ setAskFirst: (v: boolean) => void;
+}) {
return (
- <Popover open={open} onOpenChange={setOpen}>
- <PopoverTrigger asChild>
- <Button variant="ghost" size="sm" className="text-muted-foreground">
- <History /> <span className="hidden sm:inline">History</span>
- </Button>
- </PopoverTrigger>
- <PopoverContent align="end" className="w-80 p-1.5">
- {threads.data?.threads.length ? (
- <ul className="max-h-96 overflow-y-auto">
- {threads.data.threads.map((t) => (
- <li key={t.id} className="group flex items-center">
- <button
- onClick={() => {
- onPick(t.id);
- setOpen(false);
- }}
- className={cn("min-w-0 flex-1 rounded-lg px-2.5 py-2 text-left hover:bg-accent", t.id === current && "bg-accent")}
- >
- <p className="truncate text-[13px] font-medium">{t.title}</p>
- <p className="text-[11px] text-muted-foreground">{timeAgo(t.updatedAt)}</p>
- </button>
- <button
- onClick={() => {
- void actions.remove(t.id);
- if (t.id === current) onPick(null);
- }}
- className="grid size-8 shrink-0 place-items-center rounded-lg text-muted-foreground opacity-0 group-hover:opacity-100 hover:text-destructive focus:opacity-100"
- aria-label={`Delete ${t.title}`}
- >
- <Trash2 className="size-3.5" />
- </button>
- </li>
- ))}
- </ul>
- ) : (
- <p className="px-3 py-6 text-center text-[13px] text-muted-foreground">No chats yet</p>
- )}
- </PopoverContent>
- </Popover>
+ <>
+ <ModePicker value={choice} onChange={setChoice} availability={can} />
+ <EngineSwitch value={engine} onChange={setEngine} size="sm" />
+ <AskFirst checked={askFirst} onChange={setAskFirst} />
+ </>
);
}
export function AssistView() {
const router = useRouter();
- const pathname = usePathname();
const params = useSearchParams();
const id = params.get("c");
const [engine, setEngine] = useEngine();
const [askFirst, setAskFirst] = useState(true);
const [open, setOpen] = useState<{ g: Generation; i: number } | null>(null);
- const threads = useAssistThreads();
+ // "Use in a new chat" on a skill opens /assist?skill=<name>: the composer starts with "/name ".
+ const skillParam = params.get("skill");
+ const [draft, setDraft] = useState(() => ({ key: 0, text: skillParam && /^[a-z0-9-]+$/.test(skillParam) ? `/${skillParam} ` : "" }));
+ const chats = useChats({ project: "none" });
+ const can = chats.data?.availability;
+ const [choice, setChoice] = useModeChoice(can?.defaultMode);
const view = useAssistThread(id);
- const actions = useAssistActions();
+ const assist = useAssistActions();
+ const actions = useChatActions();
+ const skills = useSkills();
+ const projects = useProjects();
const end = useRef<HTMLDivElement>(null);
- const go = (next: string | null) => router.replace(next ? `${pathname}?c=${next}` : pathname, { scroll: false });
+ const go = (next: string | null) => router.replace(next ? `/assist?c=${next}` : "/assist", { scroll: false });
const thread = view.data?.thread;
+ const project = thread?.projectId ? projects.data?.find((p) => p.id === thread.projectId) : null;
+ const available = chatSkills(skills.data, project);
const all = useMemo(() => new Map((view.data?.generations ?? []).map((g) => [g.id, g])), [view.data?.generations]);
const viewable = useMemo(
() =>
@@ -472,70 +127,72 @@ export function AssistView() {
end.current?.scrollIntoView({ behavior: "smooth", block: "end" });
}, [count, status]);
- const agent = thread?.agent ?? threads.data?.agent;
- const agentBadge = agent && (
+ const start = async (text: string, attachments: string[] = []) => {
+ const t = await actions.start({ text, attachments, engine, autoApprove: !askFirst, mode: choice ?? undefined });
+ if (t.note) toast(t.note);
+ go(t.id);
+ };
+
+ const agent = thread?.agent ?? chats.data?.agent;
+ const agentBadge = thread && agent && (
<Tooltip>
<TooltipTrigger asChild>
- <Link href="/settings" className="inline-flex h-7 items-center gap-1.5 rounded-full bg-muted px-2.5 text-[12px] font-medium whitespace-nowrap text-muted-foreground hover:text-foreground">
+ <Link href="/settings" className="hidden h-7 items-center gap-1.5 rounded-full bg-muted px-2.5 text-[12px] font-medium whitespace-nowrap text-muted-foreground hover:text-foreground sm:inline-flex">
{agent === "claude" ? <Bot className="size-3" /> : <Cpu className="size-3" />}
- <span className={cn(id && "hidden sm:inline")}>{AGENT_LABEL[agent]}</span>
+ {modeLabel(thread)}
</Link>
</TooltipTrigger>
- <TooltipContent className="max-w-64">
- {AGENT_HINT[agent]}
- </TooltipContent>
+ <TooltipContent className="max-w-64">{AGENT_HINT[agent]}</TooltipContent>
</Tooltip>
);
return (
- <div className="flex h-svh min-w-0 flex-col">
- <header className="flex h-14 shrink-0 items-center gap-2 px-3 sm:px-6">
+ <div className="flex h-svh min-w-0 flex-col md:h-[calc(100svh-0.5rem)]">
+ <header className="flex h-14 shrink-0 items-center gap-1.5 px-3 sm:px-6">
<SidebarTrigger className="md:hidden" />
- <h1 className="min-w-0 truncate font-heading text-[22px] leading-none">{thread?.title ?? "Assist"}</h1>
- <div className="ml-auto flex items-center gap-1">
+ <RailButton />
+ <div className="flex min-w-0 flex-1 items-center gap-2">
+ {project && (
+ <Link href={`/assist/projects/${project.id}`} className="hidden min-w-0 shrink items-center gap-1.5 text-[13px] text-muted-foreground hover:text-foreground sm:inline-flex">
+ <ProjectDot project={project} />
+ <span className="truncate">{project.name}</span>
+ <span aria-hidden>/</span>
+ </Link>
+ )}
+ <h1 className="min-w-0 truncate font-heading text-[22px] leading-none">{thread?.title ?? "Assist"}</h1>
+ </div>
+ <div className="flex shrink-0 items-center gap-1">
{agentBadge}
- <HistoryButton current={id} onPick={go} />
{id && (
<Button variant="ghost" size="sm" onClick={() => go(null)}>
- <Plus /> <span className="hidden sm:inline">New chat</span>
+ <MessageSquarePlus /> <span className="hidden sm:inline">New chat</span>
</Button>
)}
</div>
</header>
{!id ? (
- <main className="flex min-h-0 flex-1 flex-col items-center justify-center overflow-y-auto px-3 pb-16 sm:px-6">
+ <main className="flex min-h-0 flex-1 flex-col items-center overflow-y-auto px-3 pt-[10vh] pb-16 sm:px-6 sm:pt-[14vh]">
<div className="w-full max-w-[760px]">
<div className="mb-6 text-center">
- <h2 className="font-heading text-display text-balance">What are we making?</h2>
- <p className="mt-2 text-[14px] text-muted-foreground">Describe the whole job. Assist picks the models, shows you the plan and cost, then runs every step.</p>
+ <h2 className="font-heading text-display text-balance">What are we creating today?</h2>
+ <p className="mt-2 text-[14px] text-pretty text-muted-foreground">Describe the whole job. Assist picks the models, shows you the plan and cost, then runs every step. Type / to use a skill.</p>
</div>
- <Composer
+ <AssistComposer
+ key={draft.key}
+ initialText={draft.text}
autoFocus
+ skills={available}
placeholder="e.g. “A launch campaign for my sneaker: 3 hero stills, then a 5s vertical video of the best one”"
- onSend={async (text, attachments) => {
- const t = await actions.start({ text, attachments, engine, autoApprove: !askFirst });
- go(t.id);
- }}
- footer={
- <>
- <EngineSwitch value={engine} onChange={setEngine} size="sm" />
- <AskFirst checked={askFirst} onChange={setAskFirst} />
- </>
- }
+ onSend={start}
+ footer={<NewChatControls choice={choice} setChoice={setChoice} can={can} engine={engine} setEngine={setEngine} askFirst={askFirst} setAskFirst={setAskFirst} />}
/>
- <div className="mt-4 flex flex-wrap justify-center gap-2">
+ <SkillStarters skills={available} onPick={(s) => setDraft((d) => ({ key: d.key + 1, text: `/${s.name} ` }))} />
+ <div className="mt-6 flex flex-wrap justify-center gap-2">
{SUGGESTIONS.map((s) => (
<button
key={s}
- onClick={async () => {
- try {
- const t = await actions.start({ text: s, engine, autoApprove: !askFirst });
- go(t.id);
- } catch (e) {
- toast.error((e as Error).message);
- }
- }}
+ onClick={() => start(s).catch((e) => toast.error((e as Error).message))}
className="max-w-full rounded-full border bg-background px-3.5 py-1.5 text-left text-[13px] text-muted-foreground transition hover:border-primary hover:text-foreground"
>
{s}
@@ -549,22 +206,40 @@ export function AssistView() {
<main className="min-h-0 flex-1 overflow-y-auto px-3 sm:px-6">
<div className="mx-auto w-full max-w-[760px] py-4">
{view.isError ? (
- <p className="py-20 text-center text-muted-foreground">This chat doesn&apos;t exist anymore.</p>
+ <div className="py-20 text-center">
+ <p className="font-heading text-[22px]">This chat doesn&apos;t exist anymore</p>
+ <Button variant="outline" className="mt-4" onClick={() => go(null)}>
+ Start a new chat
+ </Button>
+ </div>
) : thread ? (
- <Transcript thread={thread} all={all} onAnswer={(ok) => actions.answer(thread.id, ok)} onOpen={(g, i) => setOpen({ g, i })} />
+ <Transcript thread={thread} all={all} skills={skills.data} onAnswer={(ok) => assist.answer(thread.id, ok)} onOpen={(g, i) => setOpen({ g, i })} />
) : (
- <Loader2 className="mx-auto mt-20 animate-spin text-muted-foreground" />
+ <Loader2 className="mx-auto mt-20 animate-spin text-muted-foreground" aria-label="Loading the chat" />
)}
<div ref={end} className="h-4" />
</div>
</main>
- <div className="shrink-0 px-3 pb-4 sm:px-6">
+ <div className="shrink-0 px-3 pb-[max(1rem,env(safe-area-inset-bottom))] sm:px-6">
<div className="mx-auto w-full max-w-[760px]">
- <Composer
+ <AssistComposer
+ skills={available}
placeholder={thread?.status === "waiting" ? "Or tell me what to change…" : "Ask for changes, variations or the next step…"}
disabled={!thread || thread.status === "running"}
- onSend={(text, attachments) => actions.send(id, { text, attachments })}
- footer={thread && <AskFirst checked={!thread.autoApprove} onChange={(v) => void actions.setAutoApprove(thread.id, !v)} />}
+ onSend={(text, attachments) => assist.send(id, { text, attachments })}
+ footer={
+ thread && (
+ <>
+ <ModePicker
+ value={{ mode: thread.mode ?? "smart", agent: thread.agent, model: thread.model, effort: thread.effort }}
+ availability={can}
+ disabled={thread.status === "running"}
+ onChange={(c) => void actions.patch(thread.id, { mode: c }).catch((e) => toast.error((e as Error).message))}
+ />
+ <AskFirst checked={!thread.autoApprove} onChange={(v) => void assist.setAutoApprove(thread.id, !v)} />
+ </>
+ )
+ }
/>
</div>
</div>
@@ -583,3 +258,31 @@ export function AssistView() {
</div>
);
}
+
+/** One-tap skill starters under the empty composer: picking one types `/name ` into it. */
+export function SkillStarters({ skills, onPick, className }: { skills: SkillSummary[]; onPick: (s: SkillSummary) => void; className?: string }) {
+ const shown = [...STARTER_SKILLS.map((n) => skills.find((s) => s.name === n)).filter((s): s is SkillSummary => !!s), ...skills.filter((s) => !STARTER_SKILLS.includes(s.name))].slice(0, 6);
+ if (!shown.length) return null;
+ return (
+ <div className={cn("mt-4", className)}>
+ <div className="flex items-center justify-between px-1 pb-2">
+ <p className="text-[12px] font-medium text-muted-foreground">Start with a skill</p>
+ <Link href="/assist/skills" className="text-[12px] text-brand-text hover:underline">
+ All skills
+ </Link>
+ </div>
+ <div className="grid grid-cols-1 gap-2 sm:grid-cols-2 lg:grid-cols-3">
+ {shown.map((s) => (
+ <button key={s.name} onClick={() => onPick(s)} className="flex min-w-0 items-center gap-3 rounded-xl border bg-background p-2.5 text-left transition hover:border-primary hover:bg-accent">
+ <SkillIcon name={s.name} icon={s.icon} />
+ <span className="min-w-0">
+ <span className="block truncate text-[13px] font-medium">{s.title}</span>
+ <span className="block truncate text-[12px] text-muted-foreground">{s.description}</span>
+ </span>
+ </button>
+ ))}
+ </div>
+ </div>
+ );
+}
+
diff --git a/src/components/assist/composer.tsx b/src/components/assist/composer.tsx
new file mode 100644
index 00000000..c7a64153
--- /dev/null
+++ b/src/components/assist/composer.tsx
@@ -0,0 +1,306 @@
+"use client";
+
+import { ArrowUp, AudioLines, Loader2, Paperclip, Slash, X } from "lucide-react";
+import { nanoid } from "nanoid";
+import { useEffect, useId, useMemo, useRef, useState } from "react";
+import { toast } from "sonner";
+import { Button } from "@/components/ui/button";
+import { Kbd } from "@/components/ui/kbd";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import { uploadFile } from "@/lib/api";
+import { slashQuery, slashSkills, type SkillSummary } from "@/lib/assist";
+import type { MediaKind } from "@/lib/catalog/types";
+import { cn } from "@/lib/utils";
+import { SkillIcon } from "./skill-icon";
+
+interface Attachment {
+ id: string;
+ preview: string;
+ url?: string;
+ kind: MediaKind;
+}
+
+/**
+ * Assist's prompt box: attachments (pick, paste, drop), Enter to send, and `/` to load a skill —
+ * typing `/` at the start opens the skill menu (↑↓ to move, Enter or Tab to pick, Esc to close).
+ */
+export function AssistComposer({
+ onSend,
+ disabled,
+ placeholder,
+ autoFocus,
+ footer,
+ skills,
+ initialText = "",
+}: {
+ onSend: (text: string, attachments: string[]) => Promise<void>;
+ disabled?: boolean;
+ placeholder: string;
+ autoFocus?: boolean;
+ footer?: React.ReactNode;
+ /** Skills this chat can load (for the `/` menu). */
+ skills?: SkillSummary[];
+ initialText?: string;
+}) {
+ const [text, setText] = useState(initialText);
+ const [files, setFiles] = useState<Attachment[]>([]);
+ const [sending, setSending] = useState(false);
+ const [caret, setCaret] = useState(0);
+ const [menuIndex, setMenuIndex] = useState(0);
+ const [menuClosed, setMenuClosed] = useState(false);
+ const input = useRef<HTMLInputElement>(null);
+ const area = useRef<HTMLTextAreaElement>(null);
+ const listId = useId();
+ const uploading = files.some((f) => !f.url);
+ const ready = text.trim().length > 0 && !uploading && !sending && !disabled;
+
+ // Local previews (object URLs) are released once the upload settles, when removed, and on unmount.
+ const blobs = useRef(new Set<string>());
+ const release = (url: string) => {
+ if (blobs.current.delete(url)) URL.revokeObjectURL(url);
+ };
+ useEffect(() => {
+ const live = blobs.current;
+ return () => {
+ live.forEach((u) => URL.revokeObjectURL(u));
+ live.clear();
+ };
+ }, []);
+
+ const known = useMemo(() => new Map((skills ?? []).map((s) => [s.name, s])), [skills]);
+ const used = useMemo(() => slashSkills(text, (n) => known.has(n)).skills, [text, known]);
+ const query = slashQuery(text, caret);
+ const matches = useMemo(() => {
+ if (!query || !skills?.length) return [];
+ const q = query.query.toLowerCase();
+ const ranked = skills
+ .filter((s) => !used.includes(s.name))
+ .map((s) => ({ s, rank: s.name.startsWith(q) ? 0 : s.title.toLowerCase().startsWith(q) ? 1 : `${s.name} ${s.title} ${s.description}`.toLowerCase().includes(q) ? 2 : 9 }))
+ .filter((x) => x.rank < 9)
+ .sort((a, b) => a.rank - b.rank);
+ // Matches by name or title first; description hits only fill in when those are few.
+ const strong = ranked.filter((x) => x.rank < 2);
+ return (strong.length >= 3 ? strong : ranked).slice(0, 8).map((x) => x.s);
+ }, [query, skills, used]);
+ const menuOpen = !!query && !menuClosed && matches.length > 0;
+ const active = Math.min(menuIndex, Math.max(0, matches.length - 1));
+
+ const add = (list: FileList | null) => {
+ for (const f of Array.from(list ?? []).slice(0, 8 - files.length)) {
+ const id = nanoid(6);
+ const kind: MediaKind = f.type.startsWith("video") ? "video" : f.type.startsWith("audio") ? "audio" : "image";
+ const blob = URL.createObjectURL(f);
+ blobs.current.add(blob);
+ setFiles((xs) => [...xs, { id, kind, preview: blob }]);
+ uploadFile(f)
+ // Show the uploaded file, then let the blob go (after the element has switched over).
+ .then((a) => {
+ setFiles((xs) => xs.map((x) => (x.id === id ? { ...x, url: a.url, preview: a.url } : x)));
+ setTimeout(() => release(blob), 1500);
+ })
+ .catch((e) => {
+ toast.error((e as Error).message);
+ setFiles((xs) => xs.filter((x) => x.id !== id));
+ release(blob);
+ });
+ }
+ };
+ const remove = (f: Attachment) => {
+ setFiles((xs) => xs.filter((x) => x.id !== f.id));
+ if (f.preview.startsWith("blob:")) release(f.preview);
+ };
+
+ const pick = (s: SkillSummary) => {
+ if (!query) return;
+ const before = text.slice(0, query.start);
+ const after = text.slice(caret).replace(/^\S*/, "").replace(/^\s*/, "");
+ const next = `${before}/${s.name} ${after}`;
+ setText(next);
+ const pos = before.length + s.name.length + 2;
+ setCaret(pos);
+ setMenuIndex(0);
+ requestAnimationFrame(() => {
+ area.current?.focus();
+ area.current?.setSelectionRange(pos, pos);
+ });
+ };
+
+ const unuse = (name: string) => {
+ setText((t) => t.replace(new RegExp(`(^|\\s)/${name}(?=\\s|$)\\s*`), "$1").trimStart());
+ area.current?.focus();
+ };
+
+ const send = async () => {
+ if (!ready) return;
+ setSending(true);
+ try {
+ await onSend(text.trim(), files.map((f) => f.url!));
+ setText("");
+ setFiles([]);
+ } catch (e) {
+ toast.error((e as Error).message);
+ } finally {
+ setSending(false);
+ }
+ };
+
+ return (
+ <div
+ className="relative rounded-[20px] border bg-background p-2.5 shadow-soft transition-[border-color,box-shadow] focus-within:border-primary focus-within:ring-4 focus-within:ring-brand-faint sm:rounded-composer"
+ onDragOver={(e) => e.preventDefault()}
+ onDrop={(e) => {
+ e.preventDefault();
+ add(e.dataTransfer.files);
+ }}
+ >
+ {menuOpen && (
+ <div className="absolute inset-x-2 bottom-full z-30 mb-2 max-h-[min(18rem,42svh)] overflow-y-auto rounded-2xl border bg-popover p-1 shadow-strong" role="listbox" id={listId} aria-label="Skills">
+ <p className="px-2.5 pt-1.5 pb-1 text-[11px] font-medium text-subtle-foreground">Skills</p>
+ {matches.map((s, i) => (
+ <button
+ key={s.name}
+ type="button"
+ role="option"
+ id={`${listId}-${s.name}`}
+ aria-selected={i === active}
+ onMouseDown={(e) => e.preventDefault()}
+ onMouseEnter={() => setMenuIndex(i)}
+ onClick={() => pick(s)}
+ ref={i === active ? (el) => el?.scrollIntoView({ block: "nearest" }) : undefined}
+ className={cn("flex w-full items-center gap-2.5 rounded-xl px-2.5 py-1.5 text-left", i === active && "bg-accent")}
+ >
+ <SkillIcon name={s.name} icon={s.icon} size="sm" />
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-[13px] font-medium">
+ {s.title} <span className="font-mono text-[11px] font-normal text-muted-foreground">/{s.name}</span>
+ </span>
+ <span className="block truncate text-[12px] text-muted-foreground">{s.description}</span>
+ </span>
+ </button>
+ ))}
+ </div>
+ )}
+ {files.length > 0 && (
+ <div className="mb-2 flex flex-wrap gap-2 px-1 pt-1">
+ {files.map((f) => (
+ <div key={f.id} className="relative size-14 overflow-hidden rounded-lg border bg-muted">
+ {f.kind === "image" ? (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img src={f.preview} alt="" className="size-full object-cover" />
+ ) : f.kind === "video" ? (
+ <video src={f.preview} muted className="size-full object-cover" />
+ ) : (
+ <AudioLines className="m-auto mt-4 size-5 text-muted-foreground" />
+ )}
+ {!f.url && <Loader2 className="absolute inset-0 m-auto size-4 animate-spin text-foreground" />}
+ <button onClick={() => remove(f)} className="absolute top-0.5 right-0.5 grid size-4 place-items-center rounded-full bg-foreground/80 text-background" aria-label="Remove attachment">
+ <X className="size-2.5" />
+ </button>
+ </div>
+ ))}
+ </div>
+ )}
+ {used.length > 0 && (
+ <div className="flex flex-wrap gap-1.5 px-1.5 pt-0.5 pb-1">
+ {used.map((n) => {
+ const s = known.get(n)!;
+ return (
+ <span key={n} className="inline-flex h-7 items-center gap-1.5 rounded-full bg-brand-faint pr-1 pl-1 text-[12px] font-medium text-brand-text">
+ <SkillIcon name={s.name} icon={s.icon} size="sm" className="size-5" />
+ {s.title}
+ <button type="button" onClick={() => unuse(n)} className="grid size-5 place-items-center rounded-full hover:bg-brand-faint-hover" aria-label={`Don't use ${s.title}`}>
+ <X className="size-3" />
+ </button>
+ </span>
+ );
+ })}
+ </div>
+ )}
+ <textarea
+ ref={area}
+ value={text}
+ autoFocus={autoFocus}
+ onChange={(e) => {
+ setText(e.target.value);
+ setCaret(e.target.selectionStart ?? e.target.value.length);
+ setMenuClosed(false);
+ }}
+ onSelect={(e) => setCaret(e.currentTarget.selectionStart ?? 0)}
+ onPaste={(e) => e.clipboardData.files.length && add(e.clipboardData.files)}
+ onKeyDown={(e) => {
+ if (menuOpen) {
+ if (e.key === "ArrowDown" || e.key === "ArrowUp") {
+ e.preventDefault();
+ setMenuIndex((i) => (Math.min(i, matches.length - 1) + (e.key === "ArrowDown" ? 1 : matches.length - 1)) % matches.length);
+ return;
+ }
+ if ((e.key === "Enter" || e.key === "Tab") && !e.nativeEvent.isComposing) {
+ e.preventDefault();
+ pick(matches[active]);
+ return;
+ }
+ if (e.key === "Escape") {
+ e.preventDefault();
+ setMenuClosed(true);
+ return;
+ }
+ }
+ if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) {
+ e.preventDefault();
+ void send();
+ }
+ }}
+ rows={1}
+ placeholder={placeholder}
+ aria-label="Message"
+ role={skills?.length ? "combobox" : undefined}
+ aria-expanded={skills?.length ? menuOpen : undefined}
+ aria-controls={menuOpen ? listId : undefined}
+ aria-activedescendant={menuOpen ? `${listId}-${matches[active]?.name}` : undefined}
+ aria-autocomplete={skills?.length ? "list" : undefined}
+ className="field-sizing-content max-h-56 min-h-12 w-full resize-none bg-transparent px-2 py-1.5 text-base leading-relaxed outline-none placeholder:text-subtle-foreground"
+ />
+ <div className="mt-1 flex min-w-0 flex-wrap items-center gap-1.5">
+ <input ref={input} type="file" accept="image/*,video/*,audio/*" multiple hidden onChange={(e) => (add(e.target.files), (e.target.value = ""))} />
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <button type="button" onClick={() => input.current?.click()} className="grid size-9 shrink-0 place-items-center rounded-full text-muted-foreground hover:bg-accent hover:text-foreground" aria-label="Attach files">
+ <Paperclip className="size-4" />
+ </button>
+ </TooltipTrigger>
+ <TooltipContent>Attach photos, video or audio</TooltipContent>
+ </Tooltip>
+ {!!skills?.length && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <button
+ type="button"
+ onClick={() => {
+ const next = text.startsWith("/") ? text : `/${text ? ` ${text}` : ""}`;
+ setText(next);
+ setCaret(1);
+ setMenuClosed(false);
+ requestAnimationFrame(() => {
+ area.current?.focus();
+ area.current?.setSelectionRange(1, 1);
+ });
+ }}
+ className="hidden size-9 shrink-0 place-items-center rounded-full text-muted-foreground hover:bg-accent hover:text-foreground sm:grid"
+ aria-label="Use a skill"
+ >
+ <Slash className="size-4" />
+ </button>
+ </TooltipTrigger>
+ <TooltipContent>
+ Use a skill <Kbd>/</Kbd>
+ </TooltipContent>
+ </Tooltip>
+ )}
+ {footer}
+ <Button size="icon" className="ml-auto size-10 shrink-0 rounded-full" disabled={!ready} onClick={() => void send()} aria-label="Send">
+ {sending ? <Loader2 className="animate-spin" /> : <ArrowUp />}
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/assist/hooks.ts b/src/components/assist/hooks.ts
new file mode 100644
index 00000000..5182c58b
--- /dev/null
+++ b/src/components/assist/hooks.ts
@@ -0,0 +1,271 @@
+"use client";
+
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import type {
+ AssistAvailability,
+ AssistMemory,
+ AssistModeChoice,
+ AssistProject,
+ AssistThread,
+ AssistThreadSummary,
+ AssistThreadView,
+ MemoryCategory,
+ MemoryScope,
+ ProjectColor,
+ ProjectSource,
+ Skill,
+ SkillSummary,
+} from "@/lib/assist";
+import type { Engine } from "@/lib/catalog/types";
+
+/**
+ * React Query hooks for Assist's skills, memory, projects and chat lists (/api/assist/**).
+ * Thread transcripts stay under ["assist", id] (patched by the live generation stream in
+ * lib/api.ts); the lists here use their own keys so that reducer never mistakes them for a thread.
+ */
+
+async function json<T>(res: Response): Promise<T> {
+ if (res.status === 204) return undefined as T;
+ const body = (await res.json().catch(() => ({}))) as T & { error?: string };
+ if (!res.ok) throw Object.assign(new Error(body.error ?? `Request failed (${res.status})`), { status: res.status });
+ return body;
+}
+
+const send = 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) }));
+
+// ---------------------------------------------------------------------------
+// Chats
+
+export interface ChatList {
+ threads: AssistThreadSummary[];
+ agent: AssistThread["agent"];
+ availability: AssistAvailability;
+}
+
+/** Chats, optionally one project's (or "none": chats outside projects), with a search. */
+export function useChats(f: { project?: string | "none"; q?: string } = {}) {
+ const sp = new URLSearchParams();
+ if (f.project) sp.set("project", f.project);
+ if (f.q?.trim()) sp.set("q", f.q.trim());
+ return useQuery({
+ queryKey: ["assist-chats", f.project ?? "all", f.q?.trim() ?? ""],
+ queryFn: async () => json<ChatList>(await fetch(`/api/assist${sp.size ? `?${sp}` : ""}`)),
+ staleTime: 5_000,
+ });
+}
+
+export function useChatActions() {
+ const qc = useQueryClient();
+ const refresh = (id?: string) => {
+ void qc.invalidateQueries({ queryKey: ["assist-chats"] });
+ void qc.invalidateQueries({ queryKey: ["assist"], exact: true });
+ void qc.invalidateQueries({ queryKey: ["assist-projects"] });
+ if (id) void qc.invalidateQueries({ queryKey: ["assist", id] });
+ };
+ return {
+ start: async (body: { text: string; attachments?: string[]; engine: Engine; autoApprove: boolean; projectId?: string | null; mode?: AssistModeChoice }) => {
+ const t = await send<AssistThread & { note?: string }>("/api/assist", "POST", body);
+ qc.setQueryData<AssistThreadView>(["assist", t.id], { thread: t, generations: [] });
+ refresh(t.id);
+ return t;
+ },
+ patch: async (id: string, body: { autoApprove?: boolean; title?: string; projectId?: string | null; mode?: AssistModeChoice }) => {
+ const t = await send<AssistThread>(`/api/assist/${id}`, "PATCH", body);
+ qc.setQueryData<AssistThreadView>(["assist", id], (old) => (old ? { ...old, thread: t } : old));
+ refresh(id);
+ return t;
+ },
+ remove: async (id: string) => {
+ await send(`/api/assist/${id}`, "DELETE");
+ qc.removeQueries({ queryKey: ["assist", id] });
+ refresh();
+ },
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Skills
+
+export function useSkills() {
+ return useQuery({
+ queryKey: ["assist-skills"],
+ queryFn: async () => (await json<{ items: SkillSummary[] }>(await fetch("/api/assist/skills"))).items,
+ staleTime: 30_000,
+ });
+}
+
+export function useSkill(name: string | null) {
+ return useQuery({
+ queryKey: ["assist-skills", name],
+ enabled: !!name,
+ queryFn: async () => json<Skill>(await fetch(`/api/assist/skills/${name}`)),
+ });
+}
+
+export interface SkillForm {
+ name: string;
+ title: string;
+ description: string;
+ whenToUse?: string;
+ body: string;
+ icon?: string;
+}
+
+export function useSkillActions() {
+ const qc = useQueryClient();
+ const refresh = () => void qc.invalidateQueries({ queryKey: ["assist-skills"] });
+ return {
+ create: async (f: SkillForm) => {
+ const s = await send<Skill>("/api/assist/skills", "POST", f);
+ refresh();
+ return s;
+ },
+ update: async (name: string, f: Partial<SkillForm>) => {
+ const s = await send<Skill>(`/api/assist/skills/${name}`, "PATCH", f);
+ refresh();
+ return s;
+ },
+ toggle: async (name: string, enabled: boolean) => {
+ // Optimistic: the switch moves at once.
+ qc.setQueryData<SkillSummary[]>(["assist-skills"], (old) => old?.map((s) => (s.name === name ? { ...s, enabled } : s)));
+ try {
+ await send<Skill>(`/api/assist/skills/${name}`, "PATCH", { enabled });
+ } finally {
+ refresh();
+ }
+ },
+ duplicate: async (name: string) => {
+ const s = await send<Skill>(`/api/assist/skills/${name}/duplicate`, "POST");
+ refresh();
+ return s;
+ },
+ remove: async (name: string) => {
+ await send(`/api/assist/skills/${name}`, "DELETE");
+ refresh();
+ },
+ upload: async (file: File, replace = false) => {
+ const form = new FormData();
+ form.set("file", file);
+ const r = await json<{ skill: Skill; skipped: string[]; replaced: boolean }>(await fetch(`/api/assist/skills/upload${replace ? "?replace=1" : ""}`, { method: "POST", body: form }));
+ refresh();
+ return r;
+ },
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Memory
+
+export function useMemories(f: { scope: MemoryScope | "all"; projectId?: string | null }) {
+ const sp = new URLSearchParams({ scope: f.scope });
+ if (f.projectId) sp.set("project", f.projectId);
+ return useQuery({
+ queryKey: ["assist-memory", f.scope, f.projectId ?? null],
+ queryFn: async () => (await json<{ items: AssistMemory[] }>(await fetch(`/api/assist/memory?${sp}`))).items,
+ });
+}
+
+export function useMemoryActions() {
+ const qc = useQueryClient();
+ const refresh = () => void qc.invalidateQueries({ queryKey: ["assist-memory"] });
+ return {
+ add: async (m: { text: string; category: MemoryCategory; scope: MemoryScope; projectId?: string | null }) => {
+ const r = await send<AssistMemory>("/api/assist/memory", "POST", m);
+ refresh();
+ return r;
+ },
+ update: async (id: string, patch: { text?: string; category?: MemoryCategory }) => {
+ const r = await send<AssistMemory>(`/api/assist/memory/${id}`, "PATCH", patch);
+ refresh();
+ return r;
+ },
+ remove: async (id: string) => {
+ await send(`/api/assist/memory/${id}`, "DELETE");
+ refresh();
+ },
+ importItems: async (body: { items: { text: string; category: MemoryCategory }[]; scope: MemoryScope; projectId?: string | null }) => {
+ const r = await send<{ added: number; skipped: number }>("/api/assist/memory/import", "POST", body);
+ refresh();
+ return r;
+ },
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Projects
+
+export function useProjects() {
+ return useQuery({
+ queryKey: ["assist-projects"],
+ queryFn: async () => (await json<{ items: AssistProject[] }>(await fetch("/api/assist/projects"))).items,
+ staleTime: 10_000,
+ });
+}
+
+export function useProject(id: string | null) {
+ return useQuery({
+ queryKey: ["assist-projects", id],
+ enabled: !!id,
+ queryFn: async () => json<AssistProject>(await fetch(`/api/assist/projects/${id}`)),
+ retry: (n, e) => (e as { status?: number }).status !== 404 && n < 1,
+ });
+}
+
+export interface ProjectForm {
+ name?: string;
+ color?: ProjectColor;
+ instructions?: string;
+ skills?: string[];
+ usePersonalMemory?: boolean;
+}
+
+export type SourceForm = { kind: "link"; url: string } | { kind: "element"; elementId: string } | { kind: "text"; title?: string; text: string };
+
+export function useProjectActions() {
+ const qc = useQueryClient();
+ const refresh = (id?: string) => {
+ void qc.invalidateQueries({ queryKey: ["assist-projects"] });
+ if (id) void qc.invalidateQueries({ queryKey: ["assist-projects", id] });
+ };
+ return {
+ create: async (f: ProjectForm) => {
+ const p = await send<AssistProject>("/api/assist/projects", "POST", f);
+ refresh();
+ return p;
+ },
+ update: async (id: string, f: ProjectForm) => {
+ const p = await send<AssistProject>(`/api/assist/projects/${id}`, "PATCH", f);
+ qc.setQueryData(["assist-projects", id], p);
+ refresh(id);
+ return p;
+ },
+ remove: async (id: string) => {
+ await send(`/api/assist/projects/${id}`, "DELETE");
+ qc.removeQueries({ queryKey: ["assist-projects", id] });
+ refresh();
+ void qc.invalidateQueries({ queryKey: ["assist-chats"] });
+ },
+ addSource: async (id: string, s: SourceForm) => {
+ const r = await send<ProjectSource>(`/api/assist/projects/${id}/sources`, "POST", s);
+ refresh(id);
+ return r;
+ },
+ addFile: async (id: string, file: File) => {
+ const form = new FormData();
+ form.set("file", file);
+ const r = await json<ProjectSource>(await fetch(`/api/assist/projects/${id}/sources`, { method: "POST", body: form }));
+ refresh(id);
+ return r;
+ },
+ refreshSource: async (id: string, sourceId: string) => {
+ const r = await send<ProjectSource>(`/api/assist/projects/${id}/sources/${sourceId}/refresh`, "POST");
+ refresh(id);
+ return r;
+ },
+ removeSource: async (id: string, sourceId: string) => {
+ await send(`/api/assist/projects/${id}/sources/${sourceId}`, "DELETE");
+ refresh(id);
+ },
+ };
+}
diff --git a/src/components/assist/memory-view.tsx b/src/components/assist/memory-view.tsx
new file mode 100644
index 00000000..37a49da3
--- /dev/null
+++ b/src/components/assist/memory-view.tsx
@@ -0,0 +1,460 @@
+"use client";
+
+import { Brain, Check, ClipboardCopy, Download, Loader2, Pencil, Plus, Trash2 } from "lucide-react";
+import { useId, useMemo, 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 { Checkbox } from "@/components/ui/checkbox";
+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import { Empty, EmptyContent, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "@/components/ui/empty";
+import { Label } from "@/components/ui/label";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { SidebarTrigger } from "@/components/ui/sidebar";
+import { Skeleton } from "@/components/ui/skeleton";
+import { Textarea } from "@/components/ui/textarea";
+import { copyText } from "@/lib/clipboard";
+import { guessCategory, MEMORY_CATEGORIES, MEMORY_HINTS, MEMORY_MAX_CHARS, parseMemoryImport, type AssistMemory, type AssistProject, type MemoryCategory, type MemoryScope } from "@/lib/assist";
+import { timeAgo } from "@/lib/format";
+import { cn } from "@/lib/utils";
+import { useMemories, useMemoryActions, useProjects } from "./hooks";
+import { ProjectDot, RailButton } from "./shell";
+
+/** Where memories live: personal, or one project's. */
+type Place = { scope: "personal" } | { scope: "project"; projectId: string } | { scope: "all" };
+const placeKey = (p: Place) => (p.scope === "project" ? `project:${p.projectId}` : p.scope);
+const fromKey = (k: string): Place => (k.startsWith("project:") ? { scope: "project", projectId: k.slice(8) } : k === "all" ? { scope: "all" } : { scope: "personal" });
+
+const SOURCE_LABEL: Record<AssistMemory["source"], string> = { user: "You", agent: "Assist", import: "Imported" };
+
+/** Prompt to paste into another assistant so it lists what it remembers in a shape the import reads. */
+const EXPORT_PROMPT =
+ "List everything you remember about me — my preferences, style, how I like replies, conventions I use, my setup and tools — as short bullet points, one fact per line, grouped under the headings Preference, Style, Communication, Convention, Environment, Tooling, Troubleshooting and Notes. No commentary.";
+
+/** Memory (Supercomputer's "Learning from every chat"): typed notes, personal or per project. */
+export function MemoryView({ projectId }: { projectId?: string } = {}) {
+ const projects = useProjects();
+ const [place, setPlace] = useState<Place>(projectId ? { scope: "project", projectId } : { scope: "personal" });
+ const [category, setCategory] = useState<MemoryCategory | "all">("all");
+ const memories = useMemories({ scope: place.scope, projectId: place.scope === "project" ? place.projectId : null });
+ const [adding, setAdding] = useState(false);
+ const [importing, setImporting] = useState(false);
+ const list = (memories.data ?? []).filter((m) => category === "all" || m.category === category);
+ const counts = useMemo(() => {
+ const c = new Map<string, number>();
+ for (const m of memories.data ?? []) c.set(m.category, (c.get(m.category) ?? 0) + 1);
+ return c;
+ }, [memories.data]);
+ const projectName = (id: string | null) => projects.data?.find((p) => p.id === id);
+
+ return (
+ <div className={cn("flex min-w-0 flex-col", !projectId && "min-h-svh")}>
+ {!projectId && (
+ <header className="sticky top-0 z-20 flex h-14 items-center gap-1.5 bg-background/85 px-3 backdrop-blur sm:px-6">
+ <SidebarTrigger className="md:hidden" />
+ <RailButton />
+ <h1 className="font-heading text-[22px] leading-none">Memory</h1>
+ <div className="ml-auto flex items-center gap-1.5">
+ <Button variant="outline" size="sm" onClick={() => setImporting(true)}>
+ <Download /> <span className="hidden sm:inline">Import</span>
+ </Button>
+ <Button size="sm" onClick={() => setAdding(true)}>
+ <Plus /> <span className="hidden sm:inline">Add a memory</span>
+ <span className="sm:hidden">Add</span>
+ </Button>
+ </div>
+ </header>
+ )}
+ <main className={cn("w-full max-w-[900px] min-w-0 flex-1 px-3 pb-16 sm:px-6", projectId ? "pt-2" : "pt-4 md:pt-8")}>
+ {!projectId && <p className="max-w-2xl text-[15px] text-pretty text-muted-foreground">Learning from every chat. Assist follows these in every reply, and saves new ones when you tell it something worth keeping{" "}— it asks first while Ask first is on.</p>}
+ {projectId && (
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <p className="text-[13px] text-muted-foreground">Only this project&apos;s chats see these.</p>
+ <div className="flex gap-1.5">
+ <Button variant="outline" size="sm" onClick={() => setImporting(true)}>
+ <Download /> Import
+ </Button>
+ <Button size="sm" onClick={() => setAdding(true)}>
+ <Plus /> Add
+ </Button>
+ </div>
+ </div>
+ )}
+ <div className="mt-5 flex flex-wrap items-center gap-2">
+ {!projectId && (
+ <Select value={placeKey(place)} onValueChange={(k) => setPlace(fromKey(k))}>
+ <SelectTrigger className="h-8 rounded-full" aria-label="Whose memory">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="personal">Personal</SelectItem>
+ {projects.data?.map((p) => (
+ <SelectItem key={p.id} value={`project:${p.id}`}>
+ <ProjectDot project={p} /> {p.name}
+ </SelectItem>
+ ))}
+ <SelectItem value="all">Everything</SelectItem>
+ </SelectContent>
+ </Select>
+ )}
+ <div className="-mx-1 flex min-w-0 flex-1 gap-1 overflow-x-auto px-1 scrollbar-none" role="radiogroup" aria-label="Category">
+ {(["all", ...MEMORY_CATEGORIES] as const).map((c) => {
+ const n = c === "all" ? (memories.data?.length ?? 0) : (counts.get(c) ?? 0);
+ if (c !== "all" && !n) return null;
+ return (
+ <button
+ key={c}
+ role="radio"
+ aria-checked={category === c}
+ onClick={() => setCategory(c)}
+ className={cn(
+ "inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full px-3 text-[13px] font-medium transition-colors",
+ category === c ? "bg-brand-faint text-brand-text hover:bg-brand-faint-hover" : "bg-secondary text-secondary-foreground hover:bg-accent",
+ )}
+ >
+ {c === "all" ? "All" : c} <span className="font-mono text-[11px] opacity-70">{n}</span>
+ </button>
+ );
+ })}
+ </div>
+ </div>
+ <div className="mt-4">
+ {memories.isLoading ? (
+ <div className="space-y-2">
+ {Array.from({ length: 4 }, (_, i) => (
+ <Skeleton key={i} className="h-16 rounded-xl" />
+ ))}
+ </div>
+ ) : list.length ? (
+ <ul className="divide-y rounded-2xl border bg-background">
+ {list.map((m) => (
+ <MemoryRow key={m.id} m={m} project={place.scope === "all" ? projectName(m.projectId) : undefined} />
+ ))}
+ </ul>
+ ) : (
+ <Empty className="border py-14">
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <Brain />
+ </EmptyMedia>
+ <EmptyTitle className="font-heading text-[22px] font-normal">{category === "all" ? "Nothing remembered yet" : `No ${category.toLowerCase()} memories`}</EmptyTitle>
+ <EmptyDescription>Tell Assist “remember that I always want 9:16” in a chat, add one here, or bring over what another assistant knows about you.</EmptyDescription>
+ </EmptyHeader>
+ <EmptyContent className="flex-row justify-center">
+ <Button variant="outline" onClick={() => setImporting(true)}>
+ <Download /> Import
+ </Button>
+ <Button onClick={() => setAdding(true)}>
+ <Plus /> Add a memory
+ </Button>
+ </EmptyContent>
+ </Empty>
+ )}
+ </div>
+ </main>
+ <AddMemory open={adding} onOpenChange={setAdding} place={place} projects={projects.data ?? []} />
+ <ImportMemories open={importing} onOpenChange={setImporting} place={place} projects={projects.data ?? []} />
+ </div>
+ );
+}
+
+function MemoryRow({ m, project }: { m: AssistMemory; project?: AssistProject }) {
+ const actions = useMemoryActions();
+ const [editing, setEditing] = useState(false);
+ const [text, setText] = useState(m.text);
+ const [category, setCategory] = useState<MemoryCategory>(m.category);
+ const [confirm, setConfirm] = useState(false);
+ const [busy, setBusy] = useState(false);
+ const save = async () => {
+ setBusy(true);
+ try {
+ await actions.update(m.id, { text, category });
+ setEditing(false);
+ } catch (e) {
+ toast.error((e as Error).message);
+ } finally {
+ setBusy(false);
+ }
+ };
+ return (
+ <li className="group/mem flex gap-3 px-4 py-3">
+ {editing ? (
+ <div className="min-w-0 flex-1 space-y-2">
+ <Textarea value={text} onChange={(e) => setText(e.target.value)} maxLength={MEMORY_MAX_CHARS} rows={2} autoFocus aria-label="Memory" className="text-[14px]" />
+ <div className="flex flex-wrap items-center gap-2">
+ <CategorySelect value={category} onChange={setCategory} />
+ <div className="ml-auto flex gap-1.5">
+ <Button variant="ghost" size="sm" onClick={() => (setEditing(false), setText(m.text), setCategory(m.category))}>
+ Cancel
+ </Button>
+ <Button size="sm" onClick={() => void save()} disabled={busy || !text.trim()}>
+ {busy ? <Loader2 className="animate-spin" /> : <Check />} Save
+ </Button>
+ </div>
+ </div>
+ </div>
+ ) : (
+ <>
+ <div className="min-w-0 flex-1">
+ <p className="text-[14px] leading-relaxed break-words">{m.text}</p>
+ <p className="mt-1 flex flex-wrap items-center gap-x-2 text-[12px] text-muted-foreground">
+ <span className="font-medium text-foreground/70">{m.category}</span>
+ {project && (
+ <span className="inline-flex items-center gap-1">
+ <ProjectDot project={project} className="size-1.5" /> {project.name}
+ </span>
+ )}
+ <span>
+ {SOURCE_LABEL[m.source]} · {timeAgo(m.updatedAt)}
+ </span>
+ </p>
+ </div>
+ <div className="flex shrink-0 items-start gap-0.5 opacity-100 transition-opacity sm:opacity-0 sm:group-hover/mem:opacity-100 sm:group-focus-within/mem:opacity-100">
+ <Button variant="ghost" size="icon-sm" onClick={() => setEditing(true)} aria-label="Edit memory">
+ <Pencil />
+ </Button>
+ <Button variant="ghost" size="icon-sm" className="hover:text-destructive" onClick={() => setConfirm(true)} aria-label="Delete memory">
+ <Trash2 />
+ </Button>
+ </div>
+ </>
+ )}
+ <AlertDialog open={confirm} onOpenChange={setConfirm}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Delete memory?</AlertDialogTitle>
+ <AlertDialogDescription>“{m.text}” — Assist forgets it in every chat. This cannot be undone.</AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction variant="destructive" onClick={() => void actions.remove(m.id).catch((e) => toast.error((e as Error).message))}>
+ Delete
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </li>
+ );
+}
+
+function CategorySelect({ value, onChange, id }: { value: MemoryCategory; onChange: (c: MemoryCategory) => void; id?: string }) {
+ return (
+ <Select value={value} onValueChange={(v) => onChange(v as MemoryCategory)}>
+ <SelectTrigger id={id} size="sm" className="rounded-full" aria-label="Category">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {MEMORY_CATEGORIES.map((c) => (
+ <SelectItem key={c} value={c}>
+ {c} <span className="text-[11px] text-muted-foreground">— {MEMORY_HINTS[c]}</span>
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ );
+}
+
+/** Personal or one project (for adding and importing). */
+function ScopeSelect({ value, onChange, projects, id }: { value: string; onChange: (k: string) => void; projects: AssistProject[]; id?: string }) {
+ return (
+ <Select value={value} onValueChange={onChange}>
+ <SelectTrigger id={id} size="sm" className="rounded-full" aria-label="Keep it for">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="personal">Personal — every chat</SelectItem>
+ {projects.map((p) => (
+ <SelectItem key={p.id} value={`project:${p.id}`}>
+ <ProjectDot project={p} /> {p.name} only
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ );
+}
+
+const scopeOf = (k: string): { scope: MemoryScope; projectId: string | null } => (k.startsWith("project:") ? { scope: "project", projectId: k.slice(8) } : { scope: "personal", projectId: null });
+
+function AddMemory({ open, onOpenChange, place, projects }: { open: boolean; onOpenChange: (o: boolean) => void; place: Place; projects: AssistProject[] }) {
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="sm:max-w-[520px]">{open && <AddForm place={place} projects={projects} onDone={() => onOpenChange(false)} />}</DialogContent>
+ </Dialog>
+ );
+}
+
+function AddForm({ place, projects, onDone }: { place: Place; projects: AssistProject[]; onDone: () => void }) {
+ const actions = useMemoryActions();
+ const ids = { text: useId(), category: useId(), scope: useId() };
+ const [text, setText] = useState("");
+ const [picked, setPicked] = useState<MemoryCategory | null>(null);
+ const [scope, setScope] = useState(place.scope === "project" ? `project:${place.projectId}` : "personal");
+ const [busy, setBusy] = useState(false);
+ const category = picked ?? guessCategory(text);
+ const save = async (e: React.FormEvent) => {
+ e.preventDefault();
+ if (!text.trim()) return;
+ setBusy(true);
+ try {
+ await actions.add({ text, category, ...scopeOf(scope) });
+ toast.success("Remembered", { duration: 1500 });
+ onDone();
+ } catch (err) {
+ toast.error((err as Error).message);
+ } finally {
+ setBusy(false);
+ }
+ };
+ return (
+ <form onSubmit={save} className="space-y-4">
+ <DialogHeader>
+ <DialogTitle className="font-heading text-[24px] font-normal">Add a memory</DialogTitle>
+ <DialogDescription>One fact or rule per memory works best.</DialogDescription>
+ </DialogHeader>
+ <div className="space-y-2">
+ <Label htmlFor={ids.text}>Remember that:</Label>
+ <Textarea id={ids.text} value={text} onChange={(e) => setText(e.target.value)} maxLength={MEMORY_MAX_CHARS} rows={3} autoFocus placeholder="e.g. I post on TikTok and Reels, so default to vertical 9:16 with captions." />
+ </div>
+ <div className="flex flex-wrap gap-4">
+ <div className="space-y-1.5">
+ <Label htmlFor={ids.category} className="text-[12px]">
+ Category
+ </Label>
+ <CategorySelect id={ids.category} value={category} onChange={setPicked} />
+ </div>
+ <div className="space-y-1.5">
+ <Label htmlFor={ids.scope} className="text-[12px]">
+ Keep it for
+ </Label>
+ <ScopeSelect id={ids.scope} value={scope} onChange={setScope} projects={projects} />
+ </div>
+ </div>
+ <DialogFooter>
+ <Button type="button" variant="ghost" onClick={onDone}>
+ Cancel
+ </Button>
+ <Button type="submit" disabled={busy || !text.trim()}>
+ {busy && <Loader2 className="animate-spin" />} Remember
+ </Button>
+ </DialogFooter>
+ </form>
+ );
+}
+
+function ImportMemories({ open, onOpenChange, place, projects }: { open: boolean; onOpenChange: (o: boolean) => void; place: Place; projects: AssistProject[] }) {
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="flex max-h-[min(92svh,820px)] flex-col gap-0 overflow-hidden p-0 sm:max-w-[640px]">{open && <ImportForm place={place} projects={projects} onDone={() => onOpenChange(false)} />}</DialogContent>
+ </Dialog>
+ );
+}
+
+function ImportForm({ place, projects, onDone }: { place: Place; projects: AssistProject[]; onDone: () => void }) {
+ const actions = useMemoryActions();
+ const ids = { text: useId(), scope: useId() };
+ const [text, setText] = useState("");
+ const [items, setItems] = useState<{ text: string; category: MemoryCategory; keep: boolean }[] | null>(null);
+ const [scope, setScope] = useState(place.scope === "project" ? `project:${place.projectId}` : "personal");
+ const [busy, setBusy] = useState(false);
+ const kept = items?.filter((i) => i.keep) ?? [];
+
+ const preview = () => {
+ const parsed = parseMemoryImport(text);
+ if (!parsed.length) return void toast.error("Nothing to import — paste one memory per line or bullet");
+ setItems(parsed.map((p) => ({ ...p, keep: true })));
+ };
+ const save = async () => {
+ setBusy(true);
+ try {
+ const r = await actions.importItems({ items: kept.map(({ text, category }) => ({ text, category })), ...scopeOf(scope) });
+ toast.success(`Imported ${r.added} memor${r.added === 1 ? "y" : "ies"}`, { description: r.skipped ? `${r.skipped} were already there` : undefined });
+ onDone();
+ } catch (e) {
+ toast.error((e as Error).message);
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ return (
+ <div className="flex min-h-0 flex-1 flex-col">
+ <DialogHeader className="border-b px-5 pt-5 pb-4">
+ <DialogTitle className="font-heading text-[24px] font-normal">Import memories</DialogTitle>
+ <DialogDescription>Bring over what Claude, ChatGPT, Codex or another assistant knows about you.</DialogDescription>
+ </DialogHeader>
+ <div className="min-h-0 flex-1 space-y-4 overflow-y-auto px-5 py-4">
+ {!items ? (
+ <>
+ <div className="rounded-xl bg-muted/60 px-4 py-3 text-[13px]">
+ <p className="font-medium">1. Ask your other assistant</p>
+ <p className="mt-1 text-muted-foreground">{EXPORT_PROMPT}</p>
+ <Button
+ variant="outline"
+ size="sm"
+ className="mt-2"
+ onClick={async () => toast((await copyText(EXPORT_PROMPT)) ? "Copied" : "Couldn't copy — select the text instead", { duration: 1500 })}
+ >
+ <ClipboardCopy /> Copy this prompt
+ </Button>
+ </div>
+ <div className="space-y-2">
+ <Label htmlFor={ids.text}>2. Paste its answer</Label>
+ <Textarea id={ids.text} value={text} onChange={(e) => setText(e.target.value)} rows={9} placeholder={"## Preference\n- Prefers vertical 9:16 videos\n- Likes warm, filmic colour grading\n\n## Communication\n- Wants short answers"} className="font-mono text-[13px]" />
+ </div>
+ </>
+ ) : (
+ <>
+ <p className="text-[13px] text-muted-foreground">
+ Found {items.length}. Untick any you don&apos;t want and fix a category if it&apos;s off.
+ </p>
+ <ul className="divide-y rounded-xl border">
+ {items.map((it, i) => (
+ <li key={i} className={cn("flex items-start gap-3 px-3 py-2.5", !it.keep && "opacity-50")}>
+ <Checkbox className="mt-0.5" checked={it.keep} onCheckedChange={(v) => setItems((xs) => xs!.map((x, j) => (j === i ? { ...x, keep: !!v } : x)))} aria-label={`Import “${it.text}”`} />
+ <p className="min-w-0 flex-1 text-[13px] break-words">{it.text}</p>
+ <CategorySelect value={it.category} onChange={(c) => setItems((xs) => xs!.map((x, j) => (j === i ? { ...x, category: c } : x)))} />
+ </li>
+ ))}
+ </ul>
+ <div className="space-y-1.5">
+ <Label htmlFor={ids.scope} className="text-[12px]">
+ Keep them for
+ </Label>
+ <ScopeSelect id={ids.scope} value={scope} onChange={setScope} projects={projects} />
+ </div>
+ </>
+ )}
+ </div>
+ <DialogFooter className="mx-0 mb-0 border-t px-5 py-3">
+ {items ? (
+ <>
+ <Button variant="ghost" onClick={() => setItems(null)}>
+ Back
+ </Button>
+ <Button onClick={() => void save()} disabled={busy || !kept.length}>
+ {busy && <Loader2 className="animate-spin" />} Import {kept.length}
+ </Button>
+ </>
+ ) : (
+ <>
+ <Button variant="ghost" onClick={onDone}>
+ Cancel
+ </Button>
+ <Button onClick={preview} disabled={!text.trim()}>
+ Preview
+ </Button>
+ </>
+ )}
+ </DialogFooter>
+ </div>
+ );
+}
diff --git a/src/components/assist/mode-picker.tsx b/src/components/assist/mode-picker.tsx
new file mode 100644
index 00000000..2baf5b5c
--- /dev/null
+++ b/src/components/assist/mode-picker.tsx
@@ -0,0 +1,233 @@
+"use client";
+
+import { Bot, ChevronDown, Cpu, Gauge, Sparkles } from "lucide-react";
+import Link from "next/link";
+import { useMemo, useState, useSyncExternalStore } from "react";
+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
+import {
+ ASSIST_EFFORTS,
+ ASSIST_MODES,
+ CLAUDE_MODELS,
+ DEFAULT_CLAUDE_MODEL,
+ DEFAULT_EFFORT,
+ type AssistAgent,
+ type AssistAvailability,
+ type AssistModeChoice,
+} from "@/lib/assist";
+import { cn } from "@/lib/utils";
+
+const KEY = "fuobe:assist-mode";
+
+const listeners = new Set<() => void>();
+/** Used when the browser won't store anything (private windows, blocked storage). */
+let fallback: string | null = null;
+const readSaved = () => {
+ try {
+ return localStorage.getItem(KEY) ?? fallback;
+ } catch {
+ return fallback;
+ }
+};
+
+/** The mode new chats start in (remembered in this browser; the server's default until one is picked). */
+export function useModeChoice(defaultMode?: AssistModeChoice["mode"]): [AssistModeChoice | null, (c: AssistModeChoice) => void] {
+ const raw = useSyncExternalStore(
+ (cb) => {
+ listeners.add(cb);
+ window.addEventListener("storage", cb);
+ return () => {
+ listeners.delete(cb);
+ window.removeEventListener("storage", cb);
+ };
+ },
+ readSaved,
+ () => null,
+ );
+ const choice = useMemo(() => {
+ try {
+ const saved = JSON.parse(raw ?? "null") as AssistModeChoice | null;
+ if (saved?.mode) return saved;
+ } catch {}
+ return defaultMode ? { mode: defaultMode } : null;
+ }, [raw, defaultMode]);
+ return [
+ choice,
+ (c) => {
+ fallback = JSON.stringify(c);
+ try {
+ localStorage.setItem(KEY, fallback);
+ } catch {}
+ listeners.forEach((l) => l());
+ },
+ ];
+}
+
+export function modeChipLabel(c: AssistModeChoice | null, can?: AssistAvailability): string {
+ if (!c) return "Mode";
+ if (can?.aiOff) return "Offline";
+ if (c.mode !== "manual") return c.mode === "smart" ? "Smart" : "Free";
+ if (c.agent === "offline") return "Offline planner";
+ if (c.agent === "ollama") return c.model ?? can?.ollamaModel ?? "Local";
+ const m = CLAUDE_MODELS.find((x) => x.id === (c.model ?? DEFAULT_CLAUDE_MODEL))?.label.replace("Claude ", "") ?? "Claude";
+ return `${m} · ${ASSIST_EFFORTS.find((e) => e.id === (c.effort ?? DEFAULT_EFFORT))?.label}`;
+}
+
+const MODE_ICON = { smart: Sparkles, free: Cpu, manual: Gauge } as const;
+
+/** Supercomputer's Free / Smart / Manual, on Fuobe's agents (Claude, Ollama, the offline planner). */
+export function ModePicker({ value, onChange, availability: can, disabled }: { value: AssistModeChoice | null; onChange: (c: AssistModeChoice) => void; availability?: AssistAvailability; disabled?: boolean }) {
+ const [open, setOpen] = useState(false);
+ const mode = value?.mode ?? can?.defaultMode ?? "smart";
+ const Icon = MODE_ICON[mode];
+ const agent: AssistAgent = value?.agent ?? "claude";
+ const set = (patch: Partial<AssistModeChoice>) => onChange({ ...(value ?? { mode }), ...patch } as AssistModeChoice);
+ return (
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild>
+ <button
+ type="button"
+ disabled={disabled}
+ className="inline-flex h-8 max-w-[11rem] shrink-0 items-center gap-1.5 rounded-full bg-secondary px-3 text-[13px] font-medium text-secondary-foreground transition-colors hover:bg-accent disabled:opacity-50"
+ aria-label={`Mode: ${modeChipLabel(value, can)}`}
+ >
+ <Icon className="size-3.5 shrink-0" />
+ <span className="truncate">{modeChipLabel(value ?? { mode }, can)}</span>
+ <ChevronDown className="size-3 shrink-0 opacity-60" />
+ </button>
+ </PopoverTrigger>
+ <PopoverContent align="start" collisionPadding={12} className="w-[min(92vw,360px)] p-3">
+ {can?.aiOff && (
+ <p className="mb-3 rounded-lg bg-highlight/25 px-3 py-2 text-[12px]">
+ The AI helper is off in{" "}
+ <Link href="/settings" className="underline underline-offset-2">
+ Settings
+ </Link>
+ , so every chat uses the offline planner.
+ </p>
+ )}
+ <div role="radiogroup" aria-label="Mode" className="grid grid-cols-3 gap-1 rounded-full bg-muted p-0.5">
+ {ASSIST_MODES.map((m) => (
+ <button
+ key={m.id}
+ type="button"
+ role="radio"
+ aria-checked={mode === m.id}
+ onClick={() => set({ mode: m.id, ...(m.id === "manual" && !value?.agent && { agent: can?.claude ? "claude" : can?.ollama ? "ollama" : "offline" }) })}
+ className={cn("h-8 rounded-full text-[13px] font-medium transition-colors", mode === m.id ? "bg-background text-foreground shadow-soft" : "text-muted-foreground hover:text-foreground")}
+ >
+ {m.label}
+ </button>
+ ))}
+ </div>
+ <p className="mt-2 px-1 text-[12px] text-muted-foreground">{ASSIST_MODES.find((m) => m.id === mode)?.hint}</p>
+ {mode === "smart" && !can?.claude && (
+ <p className="mt-2 px-1 text-[12px] text-warning">
+ Needs an Anthropic API key —{" "}
+ <Link href="/settings#keys" className="underline underline-offset-2">
+ add one in Settings
+ </Link>
+ . Until then chats run in Free.
+ </p>
+ )}
+ {mode === "free" && (
+ <p className="mt-2 px-1 text-[12px] text-muted-foreground">
+ {can?.ollama ? (
+ <>
+ Runs on <span className="font-mono">{can.ollamaModel}</span> through Ollama — free, on this machine.
+ </>
+ ) : (
+ "Ollama isn't answering, so the offline planner takes simple requests. Start Ollama for a real local assistant."
+ )}
+ </p>
+ )}
+ {mode === "manual" && (
+ <div className="mt-3 space-y-3">
+ {!can?.claude && (
+ <p className="px-1 text-[12px] text-muted-foreground">
+ Claude models need an Anthropic API key —{" "}
+ <Link href="/settings#keys" className="underline underline-offset-2">
+ Settings
+ </Link>
+ .
+ </p>
+ )}
+ <div role="radiogroup" aria-label="Model" className="space-y-1">
+ {CLAUDE_MODELS.map((m) => {
+ const on = agent === "claude" && (value?.model ?? DEFAULT_CLAUDE_MODEL) === m.id;
+ return (
+ <button
+ key={m.id}
+ type="button"
+ role="radio"
+ aria-checked={on}
+ disabled={!can?.claude}
+ onClick={() => set({ agent: "claude", model: m.id })}
+ className={cn("flex w-full items-center gap-2.5 rounded-lg px-2.5 py-1.5 text-left transition-colors hover:bg-accent disabled:opacity-50 disabled:hover:bg-transparent", on && "bg-brand-faint hover:bg-brand-faint-hover")}
+ >
+ <Bot className="size-4 shrink-0 text-muted-foreground" />
+ <span className="min-w-0 flex-1">
+ <span className="block text-[13px] font-medium">{m.label}</span>
+ <span className="block text-[11px] text-muted-foreground">{m.hint}</span>
+ </span>
+ </button>
+ );
+ })}
+ {(can?.ollamaModels.length ? can.ollamaModels : can?.ollama ? [can.ollamaModel] : []).map((name) => {
+ const on = agent === "ollama" && (value?.model ?? can?.ollamaModel) === name;
+ return (
+ <button
+ key={name}
+ type="button"
+ role="radio"
+ aria-checked={on}
+ onClick={() => set({ agent: "ollama", model: name, effort: null })}
+ className={cn("flex w-full items-center gap-2.5 rounded-lg px-2.5 py-1.5 text-left transition-colors hover:bg-accent", on && "bg-brand-faint hover:bg-brand-faint-hover")}
+ >
+ <Cpu className="size-4 shrink-0 text-muted-foreground" />
+ <span className="min-w-0 flex-1">
+ <span className="block truncate font-mono text-[12px]">{name}</span>
+ <span className="block text-[11px] text-muted-foreground">Local, through Ollama · free</span>
+ </span>
+ </button>
+ );
+ })}
+ <button
+ type="button"
+ role="radio"
+ aria-checked={agent === "offline"}
+ onClick={() => set({ agent: "offline", model: null, effort: null })}
+ className={cn("flex w-full items-center gap-2.5 rounded-lg px-2.5 py-1.5 text-left transition-colors hover:bg-accent", agent === "offline" && "bg-brand-faint hover:bg-brand-faint-hover")}
+ >
+ <Gauge className="size-4 shrink-0 text-muted-foreground" />
+ <span className="min-w-0 flex-1">
+ <span className="block text-[13px] font-medium">Offline planner</span>
+ <span className="block text-[11px] text-muted-foreground">Rules, no LLM — simple requests only</span>
+ </span>
+ </button>
+ </div>
+ {agent === "claude" && (
+ <div>
+ <p className="mb-1.5 px-1 text-[12px] font-medium">Effort</p>
+ <div role="radiogroup" aria-label="Effort" className="grid grid-cols-5 gap-0.5 rounded-full bg-muted p-0.5">
+ {ASSIST_EFFORTS.map((e) => (
+ <button
+ key={e.id}
+ type="button"
+ role="radio"
+ aria-checked={(value?.effort ?? DEFAULT_EFFORT) === e.id}
+ onClick={() => set({ effort: e.id })}
+ className={cn("h-7 rounded-full text-[12px] font-medium transition-colors", (value?.effort ?? DEFAULT_EFFORT) === e.id ? "bg-background text-foreground shadow-soft" : "text-muted-foreground hover:text-foreground")}
+ >
+ {e.label}
+ </button>
+ ))}
+ </div>
+ <p className="mt-1.5 px-1 text-[11px] text-muted-foreground">Higher effort thinks longer and costs more per reply.</p>
+ </div>
+ )}
+ </div>
+ )}
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/src/components/assist/project-dialog.tsx b/src/components/assist/project-dialog.tsx
new file mode 100644
index 00000000..088f04a1
--- /dev/null
+++ b/src/components/assist/project-dialog.tsx
@@ -0,0 +1,142 @@
+"use client";
+
+import { Check, Loader2 } from "lucide-react";
+import { useId, useState } from "react";
+import { toast } from "sonner";
+import { Button } from "@/components/ui/button";
+import { Checkbox } from "@/components/ui/checkbox";
+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { Switch } from "@/components/ui/switch";
+import { Textarea } from "@/components/ui/textarea";
+import { PROJECT_COLORS, PROJECT_HUE, PROJECT_LIMITS, type AssistProject, type ProjectColor } from "@/lib/assist";
+import { cn } from "@/lib/utils";
+import { useProjectActions, useSkills } from "./hooks";
+import { SkillIcon } from "./skill-icon";
+
+/** Create or edit a project: name and colour, instructions, project skills, personal memory. */
+export function ProjectDialog({
+ open,
+ onOpenChange,
+ project,
+ onSaved,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ project?: AssistProject;
+ onSaved?: (p: AssistProject) => void;
+}) {
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="max-h-[min(90svh,760px)] gap-0 overflow-hidden p-0 sm:max-w-[560px]">
+ {/* Remount per opening so the form starts from the project as it is now. */}
+ {open && <Form project={project} onDone={(p) => (onOpenChange(false), p && onSaved?.(p))} />}
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+function Form({ project, onDone }: { project?: AssistProject; onDone: (p?: AssistProject) => void }) {
+ const actions = useProjectActions();
+ const skills = useSkills();
+ const ids = { name: useId(), instructions: useId(), memory: useId() };
+ const [name, setName] = useState(project?.name ?? "");
+ const [color, setColor] = useState<ProjectColor>(project?.color ?? "iris");
+ const [instructions, setInstructions] = useState(project?.instructions ?? "");
+ const [picked, setPicked] = useState<string[]>(project?.skills ?? []);
+ const [personal, setPersonal] = useState(project?.usePersonalMemory ?? true);
+ const [busy, setBusy] = useState(false);
+
+ const save = async (e: React.FormEvent) => {
+ e.preventDefault();
+ if (!name.trim()) return void toast.error("Give the project a name");
+ setBusy(true);
+ try {
+ const body = { name: name.trim(), color, instructions, skills: picked, usePersonalMemory: personal };
+ const p = project ? await actions.update(project.id, body) : await actions.create(body);
+ if (!project) toast.success("Project created", { duration: 1500 });
+ onDone(p);
+ } catch (err) {
+ toast.error((err as Error).message);
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const toggle = (n: string) => setPicked((xs) => (xs.includes(n) ? xs.filter((x) => x !== n) : [...xs, n]));
+
+ return (
+ <form onSubmit={save} className="flex min-h-0 flex-col">
+ <DialogHeader className="border-b px-5 pt-5 pb-4">
+ <DialogTitle className="font-heading text-[24px] font-normal">{project ? "Project settings" : "New project"}</DialogTitle>
+ <DialogDescription>Chats in a project share its instructions, sources and skills. Its memory stays inside it.</DialogDescription>
+ </DialogHeader>
+ <div className="min-h-0 flex-1 space-y-6 overflow-y-auto px-5 py-5">
+ <div className="space-y-2">
+ <Label htmlFor={ids.name}>Name</Label>
+ <div className="flex items-center gap-3">
+ <Input id={ids.name} value={name} onChange={(e) => setName(e.target.value)} maxLength={PROJECT_LIMITS.name} placeholder="e.g. Spring campaign, Cooking channel" autoFocus={!project} />
+ </div>
+ <div role="radiogroup" aria-label="Colour" className="flex flex-wrap gap-2 pt-1">
+ {PROJECT_COLORS.map((c) => (
+ <button
+ key={c}
+ type="button"
+ role="radio"
+ aria-checked={color === c}
+ aria-label={c}
+ onClick={() => setColor(c)}
+ className={cn("grid size-7 place-items-center rounded-full bg-[oklch(0.68_0.13_var(--p-hue))] ring-offset-2 ring-offset-background transition", color === c && "ring-2 ring-primary")}
+ style={{ "--p-hue": PROJECT_HUE[c] } as React.CSSProperties}
+ >
+ {color === c && <Check className="size-3.5 text-white" />}
+ </button>
+ ))}
+ </div>
+ </div>
+ <div className="space-y-2">
+ <Label htmlFor={ids.instructions}>Instructions</Label>
+ <p className="text-[12px] text-muted-foreground">Guide Assist on how to work in this project: what it should do and how it should respond.</p>
+ <Textarea
+ id={ids.instructions}
+ value={instructions}
+ onChange={(e) => setInstructions(e.target.value)}
+ maxLength={PROJECT_LIMITS.instructions}
+ rows={5}
+ placeholder="e.g. Everything is for our oat-milk brand “Oatly-ish”: warm, playful tone; vertical 9:16; teal #1E9E8F and cream; never show dairy."
+ className="min-h-28 text-[14px]"
+ />
+ </div>
+ <fieldset className="space-y-2">
+ <legend className="text-sm font-medium">Skills</legend>
+ <p className="text-[12px] text-muted-foreground">{picked.length ? `Assist can use only these ${picked.length} skill${picked.length > 1 ? "s" : ""} here.` : "None picked: every skill that's switched on is available. Pick some to limit the project to them."}</p>
+ <div className="grid max-h-56 gap-1 overflow-y-auto rounded-xl border p-1.5 sm:grid-cols-2">
+ {skills.data?.map((s) => (
+ <label key={s.name} className="flex cursor-pointer items-center gap-2.5 rounded-lg px-2 py-1.5 hover:bg-accent">
+ <Checkbox checked={picked.includes(s.name)} onCheckedChange={() => toggle(s.name)} aria-label={s.title} />
+ <SkillIcon name={s.name} icon={s.icon} size="sm" />
+ <span className="min-w-0 flex-1 truncate text-[13px]">{s.title}</span>
+ </label>
+ )) ?? <p className="p-2 text-[12px] text-muted-foreground">Loading skills…</p>}
+ </div>
+ </fieldset>
+ <div className="flex items-start justify-between gap-4">
+ <div>
+ <Label htmlFor={ids.memory}>Use my personal memory</Label>
+ <p className="mt-1 text-[12px] text-muted-foreground">Off: chats here see only this project&apos;s memory, and nothing personal carries in.</p>
+ </div>
+ <Switch id={ids.memory} checked={personal} onCheckedChange={setPersonal} />
+ </div>
+ </div>
+ <DialogFooter className="mx-0 mb-0 border-t px-5 py-3">
+ <Button type="button" variant="ghost" onClick={() => onDone()}>
+ Cancel
+ </Button>
+ <Button type="submit" disabled={busy}>
+ {busy && <Loader2 className="animate-spin" />} {project ? "Save" : "Create project"}
+ </Button>
+ </DialogFooter>
+ </form>
+ );
+}
diff --git a/src/components/assist/project-view.tsx b/src/components/assist/project-view.tsx
new file mode 100644
index 00000000..068c2c5a
--- /dev/null
+++ b/src/components/assist/project-view.tsx
@@ -0,0 +1,442 @@
+"use client";
+
+import {
+ AlertTriangle,
+ AtSign,
+ AudioLines,
+ FileText,
+ ImageIcon,
+ Link2,
+ Loader2,
+ MoreHorizontal,
+ NotebookPen,
+ Paperclip,
+ RotateCw,
+ Settings2,
+ Trash2,
+ Video,
+} from "lucide-react";
+import Link from "next/link";
+import { useRouter } from "next/navigation";
+import { useId, useRef, useState } from "react";
+import { toast } from "sonner";
+import { NotFoundState } from "@/components/empty-state";
+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, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
+import { SidebarTrigger } from "@/components/ui/sidebar";
+import { Skeleton } from "@/components/ui/skeleton";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import { Textarea } from "@/components/ui/textarea";
+import { AssistComposer } from "@/components/assist/composer";
+import { chatSkills, NewChatControls, SkillStarters } from "@/components/assist-view";
+import { useElements, useEngine } from "@/lib/api";
+import { MAX_PROJECT_SOURCES, type AssistProject, type ProjectSource, type SourceKind } from "@/lib/assist";
+import { timeAgo } from "@/lib/format";
+import { cn } from "@/lib/utils";
+import { useChatActions, useChats, useProject, useProjectActions, useSkills } from "./hooks";
+import { MemoryView } from "./memory-view";
+import { useModeChoice } from "./mode-picker";
+import { ProjectDialog } from "./project-dialog";
+import { ProjectDot, RailButton } from "./shell";
+
+const SOURCE_ICON: Record<SourceKind, typeof FileText> = { link: Link2, file: FileText, image: ImageIcon, video: Video, audio: AudioLines, element: AtSign, text: NotebookPen };
+
+/** A project's home (Supercomputer's Projects): its composer, chats, sources, memory and settings. */
+export function ProjectView({ id }: { id: string }) {
+ const project = useProject(id);
+ if (project.isLoading)
+ return (
+ <div className="mx-auto max-w-[760px] space-y-4 px-4 pt-[14vh]">
+ <Skeleton className="mx-auto h-10 w-2/3" />
+ <Skeleton className="h-28 rounded-composer" />
+ </div>
+ );
+ if (!project.data) return <NotFoundState title="No such project">It may have been deleted. Its chats are with your other chats in Assist.</NotFoundState>;
+ return <Project p={project.data} />;
+}
+
+function Project({ p }: { p: AssistProject }) {
+ const router = useRouter();
+ const [engine, setEngine] = useEngine();
+ const [askFirst, setAskFirst] = useState(true);
+ const chats = useChats({ project: p.id });
+ const can = chats.data?.availability;
+ const [choice, setChoice] = useModeChoice(can?.defaultMode);
+ const actions = useChatActions();
+ const projectActions = useProjectActions();
+ const skills = useSkills();
+ const available = chatSkills(skills.data, p);
+ const [settings, setSettings] = useState(false);
+ const [confirm, setConfirm] = useState(false);
+ const [draft, setDraft] = useState({ key: 0, text: "" });
+
+ return (
+ <div className="flex min-h-svh min-w-0 flex-col">
+ <header className="sticky top-0 z-20 flex h-14 items-center gap-1.5 bg-background/85 px-3 backdrop-blur sm:px-6">
+ <SidebarTrigger className="md:hidden" />
+ <RailButton />
+ <ProjectDot project={p} className="ml-1" />
+ <h1 className="min-w-0 truncate font-heading text-[22px] leading-none">{p.name}</h1>
+ <div className="ml-auto flex items-center gap-1">
+ <Button variant="ghost" size="sm" onClick={() => setSettings(true)}>
+ <Settings2 /> <span className="hidden sm:inline">Settings</span>
+ </Button>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="ghost" size="icon-sm" aria-label="More">
+ <MoreHorizontal />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem variant="destructive" onSelect={() => setConfirm(true)}>
+ <Trash2 /> Delete project
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ </header>
+ <main className="mx-auto w-full max-w-[860px] min-w-0 flex-1 px-3 pb-16 sm:px-6">
+ <div className="mx-auto max-w-[760px] pt-[6vh] sm:pt-[9vh]">
+ <h2 className="text-center font-heading text-display text-balance">What are we creating in {p.name}?</h2>
+ <button onClick={() => setSettings(true)} className="mx-auto mt-2 block max-w-xl text-center text-[14px] text-pretty text-muted-foreground hover:text-foreground">
+ {p.instructions ? <span className="line-clamp-2">{p.instructions}</span> : "Add instructions so every chat here knows the brief →"}
+ </button>
+ <div className="mt-6">
+ <AssistComposer
+ key={draft.key}
+ initialText={draft.text}
+ skills={available}
+ placeholder="Describe the job — chats here follow the project's instructions and can use its sources"
+ onSend={async (text, attachments) => {
+ const t = await actions.start({ text, attachments, engine, autoApprove: !askFirst, projectId: p.id, mode: choice ?? undefined });
+ if (t.note) toast(t.note);
+ router.push(`/assist?c=${t.id}`);
+ }}
+ footer={<NewChatControls choice={choice} setChoice={setChoice} can={can} engine={engine} setEngine={setEngine} askFirst={askFirst} setAskFirst={setAskFirst} />}
+ />
+ {!chats.data?.threads.length && <SkillStarters skills={available} onPick={(s) => setDraft((d) => ({ key: d.key + 1, text: `/${s.name} ` }))} />}
+ </div>
+ </div>
+ <Tabs defaultValue="chats" className="mt-10 gap-4">
+ <TabsList>
+ <TabsTrigger value="chats" className="px-3">
+ Chats <span className="font-mono text-[11px] text-muted-foreground">{chats.data?.threads.length || ""}</span>
+ </TabsTrigger>
+ <TabsTrigger value="sources" className="px-3">
+ Sources <span className="font-mono text-[11px] text-muted-foreground">{p.sources.length || ""}</span>
+ </TabsTrigger>
+ <TabsTrigger value="memory" className="px-3">
+ Memory
+ </TabsTrigger>
+ </TabsList>
+ <TabsContent value="chats">
+ {chats.isLoading ? (
+ <Skeleton className="h-24 rounded-2xl" />
+ ) : chats.data?.threads.length ? (
+ <ul className="divide-y rounded-2xl border bg-background">
+ {chats.data.threads.map((t) => (
+ <li key={t.id}>
+ <Link href={`/assist?c=${t.id}`} className="flex items-center gap-3 px-4 py-3 transition-colors hover:bg-accent">
+ <span className="min-w-0 flex-1 truncate text-[14px]">{t.title}</span>
+ <span className="shrink-0 text-[12px] text-muted-foreground">{t.status === "running" ? "Working…" : t.status === "waiting" ? "Waiting for you" : timeAgo(t.updatedAt)}</span>
+ </Link>
+ </li>
+ ))}
+ </ul>
+ ) : (
+ <p className="rounded-2xl border border-dashed px-4 py-8 text-center text-[13px] text-muted-foreground">No chats yet — start one above. It&apos;ll know this project&apos;s instructions and sources.</p>
+ )}
+ </TabsContent>
+ <TabsContent value="sources">
+ <Sources p={p} />
+ </TabsContent>
+ <TabsContent value="memory" className="-mx-3 sm:-mx-6">
+ <MemoryView projectId={p.id} />
+ </TabsContent>
+ </Tabs>
+ </main>
+ <ProjectDialog open={settings} onOpenChange={setSettings} project={p} />
+ <AlertDialog open={confirm} onOpenChange={setConfirm}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Delete {p.name}?</AlertDialogTitle>
+ <AlertDialogDescription>Its instructions, sources and project memory are deleted. Its {p.chats || ""} chat{p.chats === 1 ? "" : "s"} move to your other chats, and everything they made stays in your Library.</AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ variant="destructive"
+ onClick={async () => {
+ try {
+ await projectActions.remove(p.id);
+ toast("Project deleted", { duration: 1500 });
+ router.push("/assist");
+ } catch (e) {
+ toast.error((e as Error).message);
+ }
+ }}
+ >
+ Delete project
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </div>
+ );
+}
+
+function Sources({ p }: { p: AssistProject }) {
+ const actions = useProjectActions();
+ const elements = useElements();
+ const file = useRef<HTMLInputElement>(null);
+ const linkId = useId();
+ const [link, setLink] = useState("");
+ const [linkOpen, setLinkOpen] = useState(false);
+ const [noteOpen, setNoteOpen] = useState(false);
+ const [busy, setBusy] = useState<string | null>(null);
+ const full = p.sources.length >= MAX_PROJECT_SOURCES;
+
+ const run = async (what: string, fn: () => Promise<ProjectSource>) => {
+ setBusy(what);
+ try {
+ const s = await fn();
+ if (s.status === "error") toast.warning(`Added ${s.title}, but Assist can't read it`, { description: s.error });
+ else toast.success(`Added ${s.title}`, { duration: 1500 });
+ return true;
+ } catch (e) {
+ toast.error((e as Error).message);
+ return false;
+ } finally {
+ setBusy(null);
+ }
+ };
+
+ return (
+ <div className="space-y-3">
+ <p className="text-[13px] text-pretty text-muted-foreground">
+ {p.sources.length} of {MAX_PROJECT_SOURCES} sources. Assist sees the list in every chat here and reads a source when it needs it.
+ </p>
+ <div className="flex flex-wrap items-center gap-2">
+ <Popover open={linkOpen} onOpenChange={setLinkOpen}>
+ <PopoverTrigger asChild>
+ <Button variant="outline" size="sm" disabled={full || !!busy}>
+ {busy === "link" ? <Loader2 className="animate-spin" /> : <Link2 />} Link
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent align="end" collisionPadding={12} className="w-[min(92vw,380px)]">
+ <form
+ onSubmit={async (e) => {
+ e.preventDefault();
+ if (!link.trim()) return;
+ if (await run("link", () => actions.addSource(p.id, { kind: "link", url: /^https?:\/\//i.test(link.trim()) ? link.trim() : `https://${link.trim()}` }))) {
+ setLink("");
+ setLinkOpen(false);
+ }
+ }}
+ className="space-y-2"
+ >
+ <Label htmlFor={linkId}>Add a web page</Label>
+ <Input id={linkId} value={link} onChange={(e) => setLink(e.target.value)} placeholder="https://yourbrand.com/about" autoFocus />
+ <p className="text-[12px] text-muted-foreground">Fuobe reads the page&apos;s text now; you can refresh it later.</p>
+ <Button type="submit" size="sm" className="w-full" disabled={!link.trim() || busy === "link"}>
+ {busy === "link" && <Loader2 className="animate-spin" />} Add link
+ </Button>
+ </form>
+ </PopoverContent>
+ </Popover>
+ <input
+ ref={file}
+ type="file"
+ hidden
+ accept=".txt,.md,.markdown,.csv,.json,.srt,.vtt,.yaml,.yml,.pdf,image/*,video/*,audio/*"
+ onChange={(e) => {
+ const f = e.target.files?.[0];
+ e.target.value = "";
+ if (f) void run("file", () => actions.addFile(p.id, f));
+ }}
+ />
+ <Button variant="outline" size="sm" disabled={full || !!busy} onClick={() => file.current?.click()}>
+ {busy === "file" ? <Loader2 className="animate-spin" /> : <Paperclip />} File
+ </Button>
+ <Popover>
+ <PopoverTrigger asChild>
+ <Button variant="outline" size="sm" disabled={full || !!busy}>
+ <AtSign /> Element
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent align="end" collisionPadding={12} className="w-[min(92vw,320px)] p-1.5">
+ {elements.data?.length ? (
+ <ul className="max-h-72 overflow-y-auto">
+ {elements.data.map((el) => (
+ <li key={el.id}>
+ <button
+ onClick={() => void run("element", () => actions.addSource(p.id, { kind: "element", elementId: el.id }))}
+ disabled={p.sources.some((s) => s.elementId === el.id)}
+ className="flex w-full items-center gap-2.5 rounded-lg px-2 py-1.5 text-left hover:bg-accent disabled:opacity-50"
+ >
+ {el.references[0] ? (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img src={el.references[0]} alt="" className="size-8 shrink-0 rounded-md object-cover" />
+ ) : (
+ <span className="grid size-8 place-items-center rounded-md bg-muted">
+ <AtSign className="size-4" />
+ </span>
+ )}
+ <span className="min-w-0">
+ <span className="block truncate text-[13px] font-medium">{el.name}</span>
+ <span className="block truncate font-mono text-[11px] text-muted-foreground">@{el.handle}</span>
+ </span>
+ </button>
+ </li>
+ ))}
+ </ul>
+ ) : (
+ <p className="px-3 py-4 text-center text-[13px] text-muted-foreground">
+ No elements yet —{" "}
+ <Link href="/elements" className="text-brand-text hover:underline">
+ save a character or product
+ </Link>
+ .
+ </p>
+ )}
+ </PopoverContent>
+ </Popover>
+ <Button variant="outline" size="sm" disabled={full || !!busy} onClick={() => setNoteOpen(true)}>
+ <NotebookPen /> Note
+ </Button>
+ </div>
+ {p.sources.length ? (
+ <ul className="divide-y rounded-2xl border bg-background">
+ {p.sources.map((s) => (
+ <SourceRow key={s.id} s={s} projectId={p.id} />
+ ))}
+ </ul>
+ ) : (
+ <p className="rounded-2xl border border-dashed px-4 py-8 text-center text-[13px] text-pretty text-muted-foreground">
+ Add up to {MAX_PROJECT_SOURCES} sources — your website, a brand guide, a script, product photos, saved characters — and every chat here can use them.
+ </p>
+ )}
+ <NoteDialog open={noteOpen} onOpenChange={setNoteOpen} onSave={(title, text) => run("note", () => actions.addSource(p.id, { kind: "text", title, text }))} />
+ </div>
+ );
+}
+
+function SourceRow({ s, projectId }: { s: ProjectSource; projectId: string }) {
+ const actions = useProjectActions();
+ const [busy, setBusy] = useState(false);
+ const Icon = SOURCE_ICON[s.kind];
+ const media = s.kind === "image" && s.url;
+ return (
+ <li className="group/src flex items-start gap-3 px-4 py-3">
+ {media ? (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img src={s.url} alt="" className="size-9 shrink-0 rounded-lg object-cover" />
+ ) : (
+ <span className="grid size-9 shrink-0 place-items-center rounded-lg bg-secondary">
+ <Icon className="size-4" />
+ </span>
+ )}
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-[14px] font-medium">{s.title}</p>
+ {s.status === "error" ? (
+ <p className="mt-0.5 flex items-start gap-1 text-[12px] text-warning">
+ <AlertTriangle className="mt-0.5 size-3 shrink-0" /> {s.error}
+ </p>
+ ) : (
+ <p className="mt-0.5 line-clamp-2 text-[12px] break-words text-muted-foreground">
+ {s.kind === "link" && s.url ? `${new URL(s.url).hostname} · ` : ""}
+ {s.excerpt ?? (s.kind === "video" || s.kind === "audio" || s.kind === "image" ? "Assist can pass it to models as an input" : "")}
+ </p>
+ )}
+ </div>
+ <div className="flex shrink-0 gap-0.5 opacity-100 transition-opacity sm:opacity-0 sm:group-hover/src:opacity-100 sm:group-focus-within/src:opacity-100">
+ {s.kind === "link" && (
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ aria-label={`Fetch ${s.title} again`}
+ disabled={busy}
+ onClick={async () => {
+ setBusy(true);
+ try {
+ const r = await actions.refreshSource(projectId, s.id);
+ toast(r.status === "ready" ? "Updated" : "Still can't read it", { duration: 1500 });
+ } catch (e) {
+ toast.error((e as Error).message);
+ } finally {
+ setBusy(false);
+ }
+ }}
+ >
+ <RotateCw className={cn(busy && "animate-spin")} />
+ </Button>
+ )}
+ <Button variant="ghost" size="icon-sm" className="hover:text-destructive" aria-label={`Remove ${s.title}`} onClick={() => void actions.removeSource(projectId, s.id).catch((e) => toast.error((e as Error).message))}>
+ <Trash2 />
+ </Button>
+ </div>
+ </li>
+ );
+}
+
+function NoteDialog({ open, onOpenChange, onSave }: { open: boolean; onOpenChange: (o: boolean) => void; onSave: (title: string, text: string) => Promise<boolean> }) {
+ const ids = { title: useId(), text: useId() };
+ const [title, setTitle] = useState("");
+ const [text, setText] = useState("");
+ const [busy, setBusy] = useState(false);
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="sm:max-w-[560px]">
+ <form
+ className="space-y-4"
+ onSubmit={async (e) => {
+ e.preventDefault();
+ setBusy(true);
+ const ok = await onSave(title, text);
+ setBusy(false);
+ if (ok) {
+ setTitle("");
+ setText("");
+ onOpenChange(false);
+ }
+ }}
+ >
+ <DialogHeader>
+ <DialogTitle className="font-heading text-[24px] font-normal">Add a note</DialogTitle>
+ <DialogDescription>A brief, a script, brand rules — any text the project&apos;s chats should know.</DialogDescription>
+ </DialogHeader>
+ <div className="space-y-2">
+ <Label htmlFor={ids.title}>Title</Label>
+ <Input id={ids.title} value={title} onChange={(e) => setTitle(e.target.value)} maxLength={160} placeholder="e.g. Brand voice" />
+ </div>
+ <div className="space-y-2">
+ <Label htmlFor={ids.text}>Text</Label>
+ <Textarea id={ids.text} value={text} onChange={(e) => setText(e.target.value)} rows={8} maxLength={20_000} />
+ </div>
+ <DialogFooter>
+ <Button type="button" variant="ghost" onClick={() => onOpenChange(false)}>
+ Cancel
+ </Button>
+ <Button type="submit" disabled={busy || !text.trim()}>
+ {busy && <Loader2 className="animate-spin" />} Add note
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/src/components/assist/shell.tsx b/src/components/assist/shell.tsx
new file mode 100644
index 00000000..a8b9c798
--- /dev/null
+++ b/src/components/assist/shell.tsx
@@ -0,0 +1,263 @@
+"use client";
+
+import { Brain, FolderPlus, MessageSquarePlus, MessagesSquare, Search, Sparkles, Trash2, X } from "lucide-react";
+import Link from "next/link";
+import { usePathname, useRouter, useSearchParams } from "next/navigation";
+import { Suspense, useDeferredValue, 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 { Input } from "@/components/ui/input";
+import { Sheet, SheetContent, SheetDescription, SheetTitle } from "@/components/ui/sheet";
+import { Skeleton } from "@/components/ui/skeleton";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import { PROJECT_HUE, type AssistProject, type AssistThreadSummary } from "@/lib/assist";
+import { timeAgo } from "@/lib/format";
+import { cn } from "@/lib/utils";
+import { useChatActions, useChats, useProjects } from "./hooks";
+import { ProjectDialog } from "./project-dialog";
+
+/**
+ * Assist's own sidebar (Supercomputer's): New chat, Search, Skills, Memory, Projects and Chats.
+ * A column from xl up; below that the same list opens as a sheet from the header button.
+ */
+
+export function AssistShell({ children }: { children: React.ReactNode }) {
+ return (
+ <div className="flex min-w-0 flex-1">
+ <aside className="sticky top-0 hidden h-svh w-64 shrink-0 flex-col border-r bg-sidebar/40 xl:flex md:h-[calc(100svh-0.5rem)]" aria-label="Assist">
+ <Suspense fallback={<RailSkeleton />}>
+ <Rail />
+ </Suspense>
+ </aside>
+ <div className="min-w-0 flex-1">{children}</div>
+ </div>
+ );
+}
+
+/** The header button that opens the Assist sidebar below xl. */
+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 and memory">
+ <MessagesSquare />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>Chats, projects, skills and memory</TooltipContent>
+ </Tooltip>
+ <Sheet open={open} onOpenChange={setOpen}>
+ <SheetContent side="left" className="w-[min(86vw,320px)] gap-0 p-0" aria-describedby={undefined}>
+ <SheetTitle className="sr-only">Assist</SheetTitle>
+ <SheetDescription className="sr-only">Chats, projects, skills and memory</SheetDescription>
+ <Suspense fallback={<RailSkeleton />}>
+ <Rail onNavigate={() => setOpen(false)} />
+ </Suspense>
+ </SheetContent>
+ </Sheet>
+ </>
+ );
+}
+
+function RailSkeleton() {
+ return (
+ <div className="space-y-2 p-3">
+ <Skeleton className="h-9 rounded-full" />
+ <Skeleton className="h-8" />
+ {Array.from({ length: 6 }, (_, i) => (
+ <Skeleton key={i} className="h-7" />
+ ))}
+ </div>
+ );
+}
+
+function RailLink({ href, icon: Icon, label, active, onNavigate }: { href: string; icon: typeof Brain; label: string; active: boolean; onNavigate?: () => void }) {
+ return (
+ <Link
+ href={href}
+ onClick={onNavigate}
+ aria-current={active ? "page" : undefined}
+ className={cn("flex h-8 items-center gap-2.5 rounded-lg px-2.5 text-[13px] font-medium transition-colors hover:bg-accent", active ? "bg-accent text-foreground" : "text-muted-foreground hover:text-foreground")}
+ >
+ <Icon className="size-4" /> {label}
+ </Link>
+ );
+}
+
+export function ProjectDot({ project, className }: { project: Pick<AssistProject, "color">; className?: string }) {
+ return <span aria-hidden className={cn("inline-block size-2.5 shrink-0 rounded-full bg-[oklch(0.68_0.13_var(--p-hue))]", className)} style={{ "--p-hue": PROJECT_HUE[project.color] } as React.CSSProperties} />;
+}
+
+function Rail({ onNavigate }: { onNavigate?: () => void }) {
+ const pathname = usePathname() ?? "";
+ const params = useSearchParams();
+ const router = useRouter();
+ const current = params.get("c");
+ const [query, setQuery] = useState("");
+ const q = useDeferredValue(query.trim());
+ const chats = useChats(q ? { q } : { project: "none" });
+ const projects = useProjects();
+ const actions = useChatActions();
+ const [creating, setCreating] = useState(false);
+ const [doomed, setDoomed] = useState<AssistThreadSummary | null>(null);
+
+ const remove = async (t: AssistThreadSummary) => {
+ try {
+ await actions.remove(t.id);
+ if (t.id === current) router.replace("/assist", { scroll: false });
+ toast("Chat deleted", { duration: 1500 });
+ } catch (e) {
+ toast.error((e as Error).message);
+ }
+ };
+
+ return (
+ <div className="flex min-h-0 flex-1 flex-col">
+ <div className="space-y-2 p-3 pb-2">
+ <Button asChild variant="outline" className="h-9 w-full justify-start rounded-full">
+ <Link href="/assist" onClick={onNavigate}>
+ <MessageSquarePlus /> New chat
+ </Link>
+ </Button>
+ <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]" />
+ {query && (
+ <button onClick={() => setQuery("")} className="absolute top-1/2 right-1.5 grid size-5 -translate-y-1/2 place-items-center rounded text-muted-foreground hover:text-foreground" aria-label="Clear search">
+ <X className="size-3" />
+ </button>
+ )}
+ </div>
+ <nav className="space-y-0.5" aria-label="Assist pages">
+ <RailLink href="/assist/skills" icon={Sparkles} label="Skills" active={pathname.startsWith("/assist/skills")} onNavigate={onNavigate} />
+ <RailLink href="/assist/memory" icon={Brain} label="Memory" active={pathname.startsWith("/assist/memory")} onNavigate={onNavigate} />
+ </nav>
+ </div>
+ <div className="min-h-0 flex-1 overflow-y-auto px-3 pb-4">
+ {!q && (
+ <section aria-labelledby="rail-projects" className="mb-4">
+ <div className="flex items-center justify-between px-2.5 pt-2 pb-1">
+ <h2 id="rail-projects" className="text-[11px] font-medium tracking-wide text-subtle-foreground uppercase">
+ Projects
+ </h2>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button variant="ghost" size="icon-xs" onClick={() => setCreating(true)} aria-label="New project">
+ <FolderPlus />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>New project</TooltipContent>
+ </Tooltip>
+ </div>
+ {projects.isLoading ? (
+ <Skeleton className="mx-2.5 h-6" />
+ ) : projects.data?.length ? (
+ <ul className="space-y-0.5">
+ {projects.data.map((p) => {
+ const active = pathname === `/assist/projects/${p.id}`;
+ return (
+ <li key={p.id}>
+ <Link
+ href={`/assist/projects/${p.id}`}
+ onClick={onNavigate}
+ aria-current={active ? "page" : undefined}
+ className={cn("flex h-8 items-center gap-2.5 rounded-lg px-2.5 text-[13px] transition-colors hover:bg-accent", active ? "bg-accent font-medium" : "text-foreground/85")}
+ >
+ <ProjectDot project={p} />
+ <span className="min-w-0 flex-1 truncate">{p.name}</span>
+ {p.chats > 0 && <span className="font-mono text-[11px] text-subtle-foreground">{p.chats}</span>}
+ </Link>
+ </li>
+ );
+ })}
+ </ul>
+ ) : (
+ <button onClick={() => setCreating(true)} className="w-full rounded-lg px-2.5 py-1.5 text-left text-[12px] text-muted-foreground hover:bg-accent hover:text-foreground">
+ Group chats with shared instructions and sources →
+ </button>
+ )}
+ </section>
+ )}
+ <section aria-labelledby="rail-chats">
+ <h2 id="rail-chats" className="px-2.5 pt-2 pb-1 text-[11px] font-medium tracking-wide text-subtle-foreground uppercase">
+ {q ? `Results for “${q}”` : "Chats"}
+ </h2>
+ {chats.isLoading ? (
+ <div className="space-y-1.5 px-2.5">
+ {Array.from({ length: 4 }, (_, i) => (
+ <Skeleton key={i} className="h-6" />
+ ))}
+ </div>
+ ) : chats.data?.threads.length ? (
+ <ul className="space-y-0.5">
+ {chats.data.threads.map((t) => {
+ const project = t.projectId ? projects.data?.find((p) => p.id === t.projectId) : undefined;
+ return (
+ <li key={t.id} className="group/chat relative">
+ <Link
+ href={`/assist?c=${t.id}`}
+ onClick={onNavigate}
+ aria-current={t.id === current ? "page" : undefined}
+ className={cn("flex min-h-8 flex-col justify-center rounded-lg py-1.5 pr-8 pl-2.5 transition-colors hover:bg-accent", t.id === current && "bg-accent")}
+ >
+ <span className="truncate text-[13px]">{t.title}</span>
+ {(q || t.status !== "idle") && (
+ <span className="flex items-center gap-1.5 text-[11px] text-muted-foreground">
+ {project && <ProjectDot project={project} className="size-1.5" />}
+ {project ? `${project.name} · ` : ""}
+ {t.status === "running" ? "Working…" : t.status === "waiting" ? "Waiting for you" : timeAgo(t.updatedAt)}
+ </span>
+ )}
+ </Link>
+ <button
+ onClick={() => setDoomed(t)}
+ className="absolute top-1/2 right-1 grid size-7 -translate-y-1/2 place-items-center rounded-md text-muted-foreground opacity-100 hover:text-destructive focus-visible:opacity-100 sm:opacity-0 sm:group-hover/chat:opacity-100"
+ aria-label={`Delete ${t.title}`}
+ >
+ <Trash2 className="size-3.5" />
+ </button>
+ </li>
+ );
+ })}
+ </ul>
+ ) : (
+ <p className="px-2.5 py-2 text-[12px] text-muted-foreground">{q ? "No chats match." : "Your chats will show up here."}</p>
+ )}
+ </section>
+ </div>
+ <AlertDialog open={!!doomed} onOpenChange={(o) => !o && setDoomed(null)}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Delete this chat?</AlertDialogTitle>
+ <AlertDialogDescription>“{doomed?.title}” and its messages are removed. Everything it made stays in your Library.</AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction variant="destructive" onClick={() => doomed && void remove(doomed)}>
+ Delete
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ <ProjectDialog
+ open={creating}
+ onOpenChange={setCreating}
+ onSaved={(p) => {
+ onNavigate?.();
+ router.push(`/assist/projects/${p.id}`);
+ }}
+ />
+ </div>
+ );
+}
diff --git a/src/components/assist/skill-icon.tsx b/src/components/assist/skill-icon.tsx
new file mode 100644
index 00000000..a02f9419
--- /dev/null
+++ b/src/components/assist/skill-icon.tsx
@@ -0,0 +1,75 @@
+import {
+ AudioLines,
+ BookOpen,
+ Camera,
+ Clapperboard,
+ Copy,
+ FileText,
+ Film,
+ Languages,
+ LayoutGrid,
+ Megaphone,
+ Mic,
+ MonitorSmartphone,
+ Package,
+ Palette,
+ Scissors,
+ ShoppingBag,
+ Smartphone,
+ Sparkles,
+ UserSquare,
+ Wand2,
+ MonitorPlay,
+ type LucideIcon,
+} from "lucide-react";
+import { cn } from "@/lib/utils";
+
+/** The icon names SKILL.md files may use (`icon:`); anything else gets the wand. */
+export const SKILL_ICONS: Record<string, LucideIcon> = {
+ "audio-lines": AudioLines,
+ "book-open": BookOpen,
+ camera: Camera,
+ clapperboard: Clapperboard,
+ copy: Copy,
+ "file-text": FileText,
+ film: Film,
+ languages: Languages,
+ "layout-grid": LayoutGrid,
+ megaphone: Megaphone,
+ mic: Mic,
+ "monitor-smartphone": MonitorSmartphone,
+ package: Package,
+ palette: Palette,
+ scissors: Scissors,
+ "shopping-bag": ShoppingBag,
+ smartphone: Smartphone,
+ sparkles: Sparkles,
+ "user-square": UserSquare,
+ wand: Wand2,
+ youtube: MonitorPlay,
+};
+
+/** A stable hue per skill name, for its tile. */
+export function skillHue(name: string): number {
+ let h = 0;
+ for (const c of name) h = (h * 31 + c.charCodeAt(0)) % 360;
+ return h;
+}
+
+export function SkillIcon({ name, icon, className, size = "md" }: { name: string; icon?: string; className?: string; size?: "sm" | "md" | "lg" }) {
+ const Icon = (icon && SKILL_ICONS[icon]) || Wand2;
+ const hue = skillHue(name);
+ return (
+ <span
+ aria-hidden
+ className={cn(
+ "grid shrink-0 place-items-center rounded-lg bg-[oklch(0.94_0.045_var(--skill-hue))] text-[oklch(0.42_0.13_var(--skill-hue))] dark:bg-[oklch(0.33_0.06_var(--skill-hue))] dark:text-[oklch(0.86_0.09_var(--skill-hue))]",
+ size === "sm" ? "size-6 rounded-md" : size === "lg" ? "size-11 rounded-xl" : "size-9",
+ className,
+ )}
+ style={{ "--skill-hue": hue } as React.CSSProperties}
+ >
+ <Icon className={size === "sm" ? "size-3.5" : size === "lg" ? "size-5" : "size-4"} />
+ </span>
+ );
+}
diff --git a/src/components/assist/skills-view.tsx b/src/components/assist/skills-view.tsx
new file mode 100644
index 00000000..bef9ebbd
--- /dev/null
+++ b/src/components/assist/skills-view.tsx
@@ -0,0 +1,490 @@
+"use client";
+
+import { Copy, Download, FileUp, Loader2, MessageSquarePlus, Pencil, Plus, Search, Trash2, Upload, X } from "lucide-react";
+import Link from "next/link";
+import { usePathname, useRouter, useSearchParams } from "next/navigation";
+import { Suspense, useDeferredValue, useId, useRef, useState } from "react";
+import ReactMarkdown from "react-markdown";
+import remarkGfm from "remark-gfm";
+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 { Empty, EmptyContent, EmptyDescription, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { SidebarTrigger } from "@/components/ui/sidebar";
+import { Skeleton } from "@/components/ui/skeleton";
+import { Switch } from "@/components/ui/switch";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import { Textarea } from "@/components/ui/textarea";
+import { SKILL_LIMITS, SKILL_NAME_RE, skillSlug, type Skill, type SkillSummary } from "@/lib/assist";
+import { cn } from "@/lib/utils";
+import { useSkill, useSkillActions, useSkills, type SkillForm } from "./hooks";
+import { RailButton } from "./shell";
+import { SKILL_ICONS, SkillIcon } from "./skill-icon";
+
+/**
+ * Skills (Supercomputer's Skills page): Built-in and My skills, each switchable; create one, upload
+ * a .zip / .skill / SKILL.md, view, duplicate, download, edit and delete.
+ */
+export function SkillsView() {
+ return (
+ <Suspense fallback={null}>
+ <Skills />
+ </Suspense>
+ );
+}
+
+function Skills() {
+ const skills = useSkills();
+ const actions = useSkillActions();
+ const router = useRouter();
+ const pathname = usePathname();
+ const params = useSearchParams();
+ const viewing = params.get("skill");
+ const [tab, setTab] = useState<"builtin" | "user">("builtin");
+ const [query, setQuery] = useState("");
+ const q = useDeferredValue(query.trim().toLowerCase());
+ const [editing, setEditing] = useState<Skill | "new" | null>(null);
+ const [conflict, setConflict] = useState<File | null>(null);
+ const [uploading, setUploading] = useState(false);
+ const file = useRef<HTMLInputElement>(null);
+
+ const all = skills.data ?? [];
+ const builtin = all.filter((s) => s.source === "builtin");
+ const own = all.filter((s) => s.source === "user");
+ const filter = (list: SkillSummary[]) => (q ? list.filter((s) => `${s.name} ${s.title} ${s.description} ${s.whenToUse} ${(s.tags ?? []).join(" ")}`.toLowerCase().includes(q)) : list);
+ const open = (name: string | null) => router.replace(name ? `${pathname}?skill=${name}` : pathname, { scroll: false });
+
+ const upload = async (f: File, replace = false) => {
+ setUploading(true);
+ try {
+ const r = await actions.upload(f, replace);
+ setTab("user");
+ toast.success(`${r.replaced ? "Updated" : "Added"} /${r.skill.name}`, {
+ description: r.skipped.length ? `Left out ${r.skipped.length} file${r.skipped.length > 1 ? "s" : ""} that aren't text: ${r.skipped.slice(0, 3).join(", ")}${r.skipped.length > 3 ? "…" : ""}` : undefined,
+ action: { label: "Open", onClick: () => open(r.skill.name) },
+ });
+ } catch (e) {
+ const err = e as Error & { status?: number };
+ if (err.status === 409 && /You already have/.test(err.message)) setConflict(f);
+ else toast.error(err.message, { duration: 8000 });
+ } finally {
+ setUploading(false);
+ }
+ };
+
+ return (
+ <div className="flex min-h-svh min-w-0 flex-col">
+ <header className="sticky top-0 z-20 flex h-14 items-center gap-1.5 bg-background/85 px-3 backdrop-blur sm:px-6">
+ <SidebarTrigger className="md:hidden" />
+ <RailButton />
+ <h1 className="font-heading text-[22px] leading-none">Skills</h1>
+ <div className="ml-auto flex items-center gap-1.5">
+ <input
+ ref={file}
+ type="file"
+ accept=".zip,.skill,.md,text/markdown,application/zip"
+ hidden
+ onChange={(e) => {
+ const f = e.target.files?.[0];
+ e.target.value = "";
+ if (f) void upload(f);
+ }}
+ />
+ <Button variant="outline" size="sm" onClick={() => file.current?.click()} disabled={uploading}>
+ {uploading ? <Loader2 className="animate-spin" /> : <Upload />} <span className="hidden sm:inline">Upload</span>
+ </Button>
+ <Button size="sm" onClick={() => setEditing("new")}>
+ <Plus /> <span className="hidden sm:inline">Create skill</span>
+ <span className="sm:hidden">New</span>
+ </Button>
+ </div>
+ </header>
+ <main className="mx-auto w-full max-w-[1100px] min-w-0 flex-1 px-3 pt-4 pb-16 sm:px-6 md:pt-8">
+ <p className="max-w-2xl text-[15px] text-pretty text-muted-foreground">
+ Playbooks Assist loads for whole kinds of jobs. Type <span className="rounded bg-muted px-1 font-mono text-[13px]">/name</span> at the start of a message to use one, or let Assist pick it. Skills also reach other agents through Fuobe&apos;s MCP server.
+ </p>
+ <Tabs value={tab} onValueChange={(v) => setTab(v as typeof tab)} className="mt-6 gap-4">
+ <div className="flex flex-wrap items-center gap-3">
+ <TabsList>
+ <TabsTrigger value="builtin" className="px-3">
+ Built-in <span className="font-mono text-[11px] text-muted-foreground">{builtin.length || ""}</span>
+ </TabsTrigger>
+ <TabsTrigger value="user" className="px-3">
+ My skills <span className="font-mono text-[11px] text-muted-foreground">{own.length || ""}</span>
+ </TabsTrigger>
+ </TabsList>
+ <div className="relative ml-auto w-full sm:w-64">
+ <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 skills" aria-label="Search skills" className="h-8 rounded-full pl-8" />
+ </div>
+ </div>
+ <TabsContent value="builtin">
+ <SkillGrid loading={skills.isLoading} list={filter(builtin)} onOpen={open} onToggle={(s, v) => void actions.toggle(s.name, v).catch((e) => toast.error((e as Error).message))} empty={<NoMatch onClear={() => setQuery("")} />} />
+ </TabsContent>
+ <TabsContent value="user">
+ <SkillGrid
+ loading={skills.isLoading}
+ list={filter(own)}
+ onOpen={open}
+ onToggle={(s, v) => void actions.toggle(s.name, v).catch((e) => toast.error((e as Error).message))}
+ empty={
+ q ? (
+ <NoMatch onClear={() => setQuery("")} />
+ ) : (
+ <Empty className="border py-14">
+ <EmptyHeader>
+ <EmptyTitle className="font-heading text-[22px] font-normal">No skills of your own yet</EmptyTitle>
+ <EmptyDescription>Save a prompt or workflow you repeat as a skill, or upload one — a .zip or .skill archive, or a single SKILL.md.</EmptyDescription>
+ </EmptyHeader>
+ <EmptyContent className="flex-row justify-center">
+ <Button variant="outline" onClick={() => file.current?.click()}>
+ <FileUp /> Upload
+ </Button>
+ <Button onClick={() => setEditing("new")}>
+ <Plus /> Create skill
+ </Button>
+ </EmptyContent>
+ </Empty>
+ )
+ }
+ />
+ </TabsContent>
+ </Tabs>
+ </main>
+ <SkillDetail name={viewing} onClose={() => open(null)} onEdit={(s) => (open(null), setEditing(s))} />
+ <SkillEditor
+ skill={editing}
+ onClose={() => setEditing(null)}
+ onSaved={(s) => {
+ setTab("user");
+ open(s.name);
+ }}
+ />
+ <AlertDialog open={!!conflict} onOpenChange={(o) => !o && setConflict(null)}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Replace your skill?</AlertDialogTitle>
+ <AlertDialogDescription>You already have a skill with this name. Uploading replaces its instructions and files.</AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Keep mine</AlertDialogCancel>
+ <AlertDialogAction onClick={() => conflict && void upload(conflict, true)}>Replace</AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </div>
+ );
+}
+
+function NoMatch({ onClear }: { onClear: () => void }) {
+ return (
+ <div className="rounded-xl border border-dashed py-12 text-center">
+ <p className="text-[14px] text-muted-foreground">No skills match.</p>
+ <Button variant="link" onClick={onClear}>
+ Clear the search
+ </Button>
+ </div>
+ );
+}
+
+function SkillGrid({ list, loading, onOpen, onToggle, empty }: { list: SkillSummary[]; loading: boolean; onOpen: (name: string) => void; onToggle: (s: SkillSummary, on: boolean) => void; empty: React.ReactNode }) {
+ if (loading)
+ return (
+ <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
+ {Array.from({ length: 6 }, (_, i) => (
+ <Skeleton key={i} className="h-36 rounded-2xl" />
+ ))}
+ </div>
+ );
+ if (!list.length) return <>{empty}</>;
+ return (
+ <ul className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
+ {list.map((s) => (
+ <li key={s.name} className={cn("group/skill relative flex min-w-0 flex-col rounded-2xl border bg-background p-4 transition hover:border-border-strong hover:shadow-soft", !s.enabled && "opacity-70")}>
+ <div className="flex items-start gap-3">
+ <SkillIcon name={s.name} icon={s.icon} />
+ <div className="min-w-0 flex-1">
+ <h2 className="truncate text-[14px] font-medium">
+ <button onClick={() => onOpen(s.name)} className="block w-full truncate text-left after:absolute after:inset-0 after:rounded-2xl outline-none focus-visible:after:ring-2 focus-visible:after:ring-ring">
+ {s.title}
+ </button>
+ </h2>
+ <p className="truncate font-mono text-[11px] text-muted-foreground">/{s.name}</p>
+ </div>
+ <Switch size="sm" checked={s.enabled} onCheckedChange={(v) => onToggle(s, v)} aria-label={`${s.enabled ? "Switch off" : "Switch on"} ${s.title}`} className="relative z-10" />
+ </div>
+ <p className="mt-3 line-clamp-3 text-[13px] text-muted-foreground">{s.description}</p>
+ {s.files.length > 0 && <p className="mt-auto pt-3 text-[11px] text-subtle-foreground">+ {s.files.length} file{s.files.length > 1 ? "s" : ""}</p>}
+ </li>
+ ))}
+ </ul>
+ );
+}
+
+function SkillDetail({ name, onClose, onEdit }: { name: string | null; onClose: () => void; onEdit: (s: Skill) => void }) {
+ const skill = useSkill(name);
+ const actions = useSkillActions();
+ const router = useRouter();
+ const [confirm, setConfirm] = useState(false);
+ const s = skill.data;
+ return (
+ <Dialog open={!!name} onOpenChange={(o) => !o && onClose()}>
+ <DialogContent className="flex max-h-[min(92svh,860px)] flex-col gap-0 overflow-hidden p-0 sm:max-w-[760px]">
+ {!s ? (
+ <div className="space-y-3 p-6">
+ <DialogTitle className="sr-only">Skill</DialogTitle>
+ {skill.isError ? <p className="text-[14px] text-muted-foreground">This skill doesn&apos;t exist anymore.</p> : <Skeleton className="h-40" />}
+ </div>
+ ) : (
+ <>
+ <DialogHeader className="flex-row items-start gap-3 border-b px-5 pt-5 pb-4 text-left">
+ <SkillIcon name={s.name} icon={s.icon} size="lg" />
+ <div className="min-w-0 flex-1">
+ <DialogTitle className="font-heading text-[24px] leading-tight font-normal">{s.title}</DialogTitle>
+ <DialogDescription className="mt-1">{s.description}</DialogDescription>
+ <p className="mt-1.5 font-mono text-[11px] text-muted-foreground">
+ /{s.name} · {s.source === "builtin" ? "Built-in" : "Yours"}
+ {s.studio && (
+ <>
+ {" · "}
+ <Link href={s.studio} className="text-brand-text hover:underline">
+ Open the studio
+ </Link>
+ </>
+ )}
+ </p>
+ </div>
+ </DialogHeader>
+ <div className="min-h-0 flex-1 overflow-y-auto px-5 py-4">
+ {s.whenToUse && (
+ <div className="mb-4 rounded-xl bg-muted/60 px-4 py-3 text-[13px]">
+ <p className="font-medium">When Assist uses it</p>
+ <p className="mt-0.5 text-muted-foreground">{s.whenToUse}</p>
+ </div>
+ )}
+ <article className="prose-fuobe min-w-0 text-[14px] break-words">
+ <ReactMarkdown remarkPlugins={[remarkGfm]}>{s.body}</ReactMarkdown>
+ </article>
+ {s.files.length > 0 && (
+ <div className="mt-4 border-t pt-3">
+ <p className="text-[12px] font-medium">Files</p>
+ <ul className="mt-1 space-y-0.5 font-mono text-[12px] text-muted-foreground">
+ {s.files.map((f) => (
+ <li key={f.path}>
+ {f.path} <span className="text-subtle-foreground">· {f.size < 1024 ? `${f.size} B` : `${(f.size / 1024).toFixed(1)} KB`}</span>
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
+ </div>
+ <DialogFooter className="mx-0 mb-0 flex-row flex-wrap items-center gap-2 border-t px-5 py-3 sm:justify-between">
+ <div className="flex flex-wrap gap-1.5">
+ <Button variant="ghost" size="sm" asChild>
+ <a href={`/api/assist/skills/${s.name}/download`} download>
+ <Download /> SKILL.md
+ </a>
+ </Button>
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={async () => {
+ try {
+ const c = await actions.duplicate(s.name);
+ toast.success(`Copied as /${c.name}`, { duration: 2000 });
+ onEdit(c);
+ } catch (e) {
+ toast.error((e as Error).message);
+ }
+ }}
+ >
+ <Copy /> Duplicate
+ </Button>
+ {s.source === "user" && (
+ <>
+ <Button variant="ghost" size="sm" onClick={() => onEdit(s)}>
+ <Pencil /> Edit
+ </Button>
+ <Button variant="ghost" size="sm" className="text-destructive hover:text-destructive" onClick={() => setConfirm(true)}>
+ <Trash2 /> Delete
+ </Button>
+ </>
+ )}
+ </div>
+ <Button size="sm" onClick={() => router.push(`/assist?skill=${s.name}`)} disabled={!s.enabled}>
+ <MessageSquarePlus /> Use in a new chat
+ </Button>
+ </DialogFooter>
+ <AlertDialog open={confirm} onOpenChange={setConfirm}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Delete /{s.name}?</AlertDialogTitle>
+ <AlertDialogDescription>Assist won&apos;t be able to use it anymore. This can&apos;t be undone — download the SKILL.md first if you might want it back.</AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ variant="destructive"
+ onClick={async () => {
+ try {
+ await actions.remove(s.name);
+ toast("Skill deleted", { duration: 1500 });
+ onClose();
+ } catch (e) {
+ toast.error((e as Error).message);
+ }
+ }}
+ >
+ Delete
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </>
+ )}
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+const ICON_CHOICES = Object.keys(SKILL_ICONS);
+
+function SkillEditor({ skill, onClose, onSaved }: { skill: Skill | "new" | null; onClose: () => void; onSaved: (s: Skill) => void }) {
+ return (
+ <Dialog open={!!skill} onOpenChange={(o) => !o && onClose()}>
+ <DialogContent className="flex max-h-[min(94svh,900px)] flex-col gap-0 overflow-hidden p-0 sm:max-w-[680px]">
+ {skill && <EditorForm key={skill === "new" ? "new" : skill.name} skill={skill === "new" ? null : skill} onClose={onClose} onSaved={onSaved} />}
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+function EditorForm({ skill, onClose, onSaved }: { skill: Skill | null; onClose: () => void; onSaved: (s: Skill) => void }) {
+ const actions = useSkillActions();
+ const ids = { title: useId(), name: useId(), description: useId(), when: useId(), body: useId() };
+ const [form, setForm] = useState<SkillForm>({
+ name: skill?.name ?? "",
+ title: skill?.title ?? "",
+ description: skill?.description ?? "",
+ whenToUse: skill?.whenToUse ?? "",
+ body: skill?.body ?? "",
+ icon: skill?.icon ?? "wand",
+ });
+ const [nameTouched, setNameTouched] = useState(!!skill);
+ const [error, setError] = useState<string | null>(null);
+ const [busy, setBusy] = useState(false);
+ const set = (patch: Partial<SkillForm>) => setForm((f) => ({ ...f, ...patch }));
+ const nameOk = SKILL_NAME_RE.test(form.name);
+
+ const save = async (e: React.FormEvent) => {
+ e.preventDefault();
+ setError(null);
+ if (!form.title.trim() || !form.description.trim() || !form.body.trim()) return setError("Give the skill a title, a description and instructions.");
+ if (!nameOk) return setError("The name can use lowercase letters, numbers and hyphens, e.g. product-photos.");
+ setBusy(true);
+ try {
+ const s = skill ? await actions.update(skill.name, form) : await actions.create(form);
+ toast.success(skill ? "Saved" : `Created /${s.name}`, { duration: 1500 });
+ onClose();
+ onSaved(s);
+ } catch (err) {
+ setError((err as Error).message);
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ return (
+ <form onSubmit={save} className="flex min-h-0 flex-1 flex-col">
+ <DialogHeader className="border-b px-5 pt-5 pb-4">
+ <DialogTitle className="font-heading text-[24px] font-normal">{skill ? `Edit ${skill.title}` : "Create a skill"}</DialogTitle>
+ <DialogDescription>Save a reusable prompt or workflow. Assist reads the instructions whenever the skill is used.</DialogDescription>
+ </DialogHeader>
+ <div className="min-h-0 flex-1 space-y-5 overflow-y-auto px-5 py-5">
+ <div className="grid gap-4 sm:grid-cols-[1fr_200px]">
+ <div className="space-y-2">
+ <Label htmlFor={ids.title}>Title</Label>
+ <Input
+ id={ids.title}
+ value={form.title}
+ maxLength={SKILL_LIMITS.title}
+ autoFocus
+ placeholder="e.g. Recipe reels"
+ onChange={(e) => set({ title: e.target.value, ...(!nameTouched && { name: skillSlug(e.target.value) }) })}
+ />
+ </div>
+ <div className="space-y-2">
+ <Label htmlFor={ids.name}>Name</Label>
+ <div className="relative">
+ <span className="pointer-events-none absolute top-1/2 left-2.5 -translate-y-1/2 font-mono text-[13px] text-muted-foreground">/</span>
+ <Input
+ id={ids.name}
+ value={form.name}
+ maxLength={SKILL_LIMITS.name}
+ aria-invalid={!!form.name && !nameOk}
+ className="pl-5 font-mono text-[13px]"
+ onChange={(e) => (setNameTouched(true), set({ name: e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, "-") }))}
+ />
+ </div>
+ </div>
+ </div>
+ <div className="space-y-2">
+ <Label htmlFor={ids.description}>What it does</Label>
+ <Textarea id={ids.description} rows={2} value={form.description} maxLength={SKILL_LIMITS.description} placeholder="e.g. Turns a recipe into a 30-second vertical cooking reel with captions." onChange={(e) => set({ description: e.target.value })} />
+ </div>
+ <div className="space-y-2">
+ <Label htmlFor={ids.when}>When Assist should use it</Label>
+ <Textarea id={ids.when} rows={2} value={form.whenToUse} maxLength={SKILL_LIMITS.whenToUse} placeholder="e.g. The user shares a recipe or asks for a cooking video." onChange={(e) => set({ whenToUse: e.target.value })} />
+ </div>
+ <div className="space-y-2">
+ <Label htmlFor={ids.body}>Instructions</Label>
+ <p className="text-[12px] text-muted-foreground">Markdown. Steps, models to prefer, prompt templates, formats, checks — whatever you&apos;d tell a teammate.</p>
+ <Textarea
+ id={ids.body}
+ rows={12}
+ value={form.body}
+ maxLength={SKILL_LIMITS.body}
+ placeholder={"# Recipe reels\n\n1. Ask for the recipe if it isn't attached.\n2. Write a 30-second script…\n3. …"}
+ className="min-h-64 font-mono text-[13px] leading-relaxed"
+ onChange={(e) => set({ body: e.target.value })}
+ />
+ </div>
+ <fieldset className="space-y-2">
+ <legend className="text-sm font-medium">Icon</legend>
+ <div role="radiogroup" aria-label="Icon" className="flex flex-wrap gap-1.5">
+ {ICON_CHOICES.map((i) => (
+ <button key={i} type="button" role="radio" aria-checked={form.icon === i} aria-label={i} onClick={() => set({ icon: i })} className={cn("rounded-xl p-0.5 ring-offset-2 ring-offset-background", form.icon === i && "ring-2 ring-primary")}>
+ <SkillIcon name={form.name || "new"} icon={i} size="sm" className="size-8" />
+ </button>
+ ))}
+ </div>
+ </fieldset>
+ {error && (
+ <p role="alert" className="flex items-start gap-2 rounded-xl bg-destructive/10 px-3 py-2 text-[13px] text-destructive">
+ <X className="mt-0.5 size-3.5 shrink-0" /> {error}
+ </p>
+ )}
+ </div>
+ <DialogFooter className="mx-0 mb-0 border-t px-5 py-3">
+ <Button type="button" variant="ghost" onClick={onClose}>
+ Cancel
+ </Button>
+ <Button type="submit" disabled={busy}>
+ {busy && <Loader2 className="animate-spin" />} {skill ? "Save" : "Create skill"}
+ </Button>
+ </DialogFooter>
+ </form>
+ );
+}
diff --git a/src/components/assist/transcript.tsx b/src/components/assist/transcript.tsx
new file mode 100644
index 00000000..5ec721cf
--- /dev/null
+++ b/src/components/assist/transcript.tsx
@@ -0,0 +1,256 @@
+"use client";
+
+import { ArrowUpRight, AudioLines, Box, Brain, Check, CircleAlert, Clapperboard, FileText, ImageIcon, Loader2, Search, Sparkles, Video } from "lucide-react";
+import Link from "next/link";
+import { useState } from "react";
+import { toast } from "sonner";
+import { Button } from "@/components/ui/button";
+import { FailedTile, MediaThumb, PendingTile, tileRatio } from "@/components/studio/feed";
+import { useCreateGeneration } from "@/lib/api";
+import type { AssistItem, AssistThread, PlannedJob, SkillSummary } from "@/lib/assist";
+import { OPERATION_LABELS, type Generation, type MediaKind, type Operation } from "@/lib/catalog/types";
+import { formatCost } from "@/lib/format";
+import { cn } from "@/lib/utils";
+import { SkillIcon } from "./skill-icon";
+
+const KIND_ICON: Record<MediaKind | "storyboard" | "memory", typeof ImageIcon> = { image: ImageIcon, video: Video, audio: AudioLines, text: FileText, model3d: Box, storyboard: Clapperboard, memory: Brain };
+
+/** Paragraphs, "- " bullets and **bold** — the little markdown the assistant uses. */
+export function Prose({ text }: { text: string }) {
+ const inline = (s: string) => s.split(/(\*\*[^*]+\*\*)/g).map((p, i) => (p.startsWith("**") && p.endsWith("**") ? <strong key={i}>{p.slice(2, -2)}</strong> : p));
+ return (
+ <div className="space-y-2.5 text-[15px] leading-relaxed">
+ {text.split(/\n{2,}/).map((para, i) => {
+ const lines = para.split("\n");
+ if (lines.every((l) => /^\s*([-*•]|\d+\.)\s/.test(l))) {
+ return (
+ <ul key={i} className="list-disc space-y-1 pl-5 marker:text-muted-foreground">
+ {lines.map((l, j) => (
+ <li key={j}>{inline(l.replace(/^\s*([-*•]|\d+\.)\s/, ""))}</li>
+ ))}
+ </ul>
+ );
+ }
+ return (
+ <p key={i} className="break-words whitespace-pre-wrap">
+ {inline(para)}
+ </p>
+ );
+ })}
+ </div>
+ );
+}
+
+function jobPrice(j: PlannedJob): string {
+ if (j.error) return "—";
+ if (j.op === "memory") return "";
+ if (j.demo) return "Demo";
+ if (j.costUsd === 0) return "Free";
+ return j.costUsd === null ? "Price varies" : formatCost(j.costUsd);
+}
+
+function jobLine(j: PlannedJob): string {
+ if (j.op === "storyboard") return `Storyboard · ${j.count} frames`;
+ if (j.op === "memory") return j.note ?? "Memory";
+ const op = OPERATION_LABELS[j.op as Operation] ?? j.op;
+ return [j.note && j.note !== op ? j.note : op, j.count > 1 ? `${j.count} takes` : ""].filter(Boolean).join(" · ");
+}
+
+export function ApprovalCard({ item, live, onAnswer }: { item: Extract<AssistItem, { role: "approval" }>; live: boolean; onAnswer: (ok: boolean) => Promise<void> }) {
+ const [busy, setBusy] = useState<boolean | null>(null);
+ const runnable = item.jobs.some((j) => !j.error);
+ const memoryOnly = item.jobs.length > 0 && item.jobs.every((j) => j.op === "memory");
+ const allDemo = item.jobs.every((j) => j.demo || j.error || j.op === "memory");
+ const total = memoryOnly
+ ? "Saved to memory for future chats"
+ : allDemo
+ ? "Demo run — no provider connected"
+ : item.totalUsd === null
+ ? "Some prices vary"
+ : item.totalUsd === 0
+ ? "Free"
+ : `≈ ${formatCost(item.totalUsd)}`;
+ const answer = async (ok: boolean) => {
+ setBusy(ok);
+ try {
+ await onAnswer(ok);
+ } catch (e) {
+ toast.error((e as Error).message);
+ } finally {
+ setBusy(null);
+ }
+ };
+ // Long studio plans (a dub, a faceless episode) fold after six steps.
+ const [all, setAll] = useState(false);
+ const shown = all ? item.jobs : item.jobs.slice(0, 6);
+ return (
+ <div className={cn("animate-fade-up overflow-hidden rounded-2xl border bg-background shadow-soft", item.status !== "pending" && "opacity-80")}>
+ <div className="flex items-center gap-2 border-b bg-muted/40 px-4 py-2.5">
+ {memoryOnly ? <Brain className="size-3.5 text-brand-text" /> : <Sparkles className="size-3.5 text-brand-text" />}
+ <p className="min-w-0 flex-1 truncate text-[13px] font-medium">{item.summary}</p>
+ {item.status === "approved" && (
+ <span className="inline-flex items-center gap-1 text-[12px] font-medium text-brand-text">
+ <Check className="size-3" /> {memoryOnly ? "Saved" : "Approved"}
+ </span>
+ )}
+ {item.status === "declined" && <span className="text-[12px] text-muted-foreground">Skipped</span>}
+ </div>
+ <ul className="divide-y">
+ {shown.map((j, i) => {
+ const Icon = KIND_ICON[j.op === "storyboard" ? "storyboard" : j.op === "memory" ? "memory" : j.kind];
+ return (
+ <li key={i} className="flex gap-3 px-4 py-3">
+ <span className="mt-0.5 grid size-8 shrink-0 place-items-center rounded-lg bg-secondary">
+ <Icon className="size-4" />
+ </span>
+ <div className="min-w-0 flex-1">
+ <p className="text-[13px] font-medium break-words">
+ {j.modelName}
+ <span className="font-normal text-muted-foreground">
+ {" · "}
+ {jobLine(j)}
+ </span>
+ </p>
+ <p className={cn("mt-0.5 text-[13px] break-words", j.op === "memory" ? "text-foreground" : "line-clamp-2 text-muted-foreground")}>{j.prompt}</p>
+ {j.error && (
+ <p className="mt-1 flex items-start gap-1 text-[12px] text-destructive">
+ <CircleAlert className="mt-0.5 size-3 shrink-0" /> {j.error}
+ </p>
+ )}
+ </div>
+ <span className="shrink-0 font-mono text-[12px] text-muted-foreground">{jobPrice(j)}</span>
+ </li>
+ );
+ })}
+ </ul>
+ {item.jobs.length > 6 && (
+ <button onClick={() => setAll((v) => !v)} className="w-full border-t px-4 py-2 text-left text-[12px] font-medium text-brand-text hover:bg-accent">
+ {all ? "Show fewer steps" : `Show all ${item.jobs.length} steps`}
+ </button>
+ )}
+ <div className="flex flex-wrap items-center gap-2 border-t px-4 py-2.5">
+ <p className="text-[12px] text-muted-foreground">{total}</p>
+ {live && item.status === "pending" && (
+ <div className="ml-auto flex gap-1.5">
+ <Button variant="ghost" size="sm" disabled={busy !== null} onClick={() => void answer(false)}>
+ Not now
+ </Button>
+ <Button size="sm" disabled={busy !== null || !runnable} onClick={() => void answer(true)}>
+ {busy ? <Loader2 className="animate-spin" /> : <Check />} {memoryOnly ? "Remember" : `Run${item.totalUsd && !allDemo ? ` · ${formatCost(item.totalUsd)}` : ""}`}
+ </Button>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
+
+export function GenerationCards({ ids, all, storyboard, onOpen }: { ids: string[]; all: Map<string, Generation>; storyboard?: boolean; onOpen: (g: Generation, i: number) => void }) {
+ const create = useCreateGeneration();
+ const gens = ids.map((id) => all.get(id)).filter((g): g is Generation => !!g);
+ if (!gens.length) return null;
+ const tiles = gens.flatMap((g) => {
+ const ratio = tileRatio(g);
+ if (g.status === "succeeded") {
+ return g.outputs.map((o, i) => (
+ <button key={`${g.id}-${i}`} onClick={() => onOpen(g, i)} className="group relative overflow-hidden rounded-xl bg-muted" style={{ aspectRatio: ratio }} aria-label={`Open ${g.request.prompt?.slice(0, 60) || "result"}`}>
+ <MediaThumb output={o} className="transition duration-300 group-hover:scale-[1.02]" />
+ {g.provider === "mock" && <span className="absolute top-2 right-2 rounded-full bg-background/80 px-2 py-0.5 text-[10px] font-medium">Demo</span>}
+ </button>
+ ));
+ }
+ if (g.status === "failed" || g.status === "canceled") {
+ return [<FailedTile key={g.id} g={g} ratio={ratio} onRetry={() => create.mutate(g.request, { onError: (e) => toast.error((e as Error).message) })} />];
+ }
+ return Array.from({ length: Math.max(1, g.request.params?.numOutputs ?? 1) }, (_, i) => <PendingTile key={`${g.id}-${i}`} g={g} ratio={ratio} />);
+ });
+ const portrait = tileRatio(gens[0]) < 1;
+ return (
+ <div className={cn("grid gap-2", storyboard ? "grid-cols-2 sm:grid-cols-4" : portrait ? "grid-cols-2 sm:grid-cols-3" : tiles.length === 1 ? "grid-cols-1 sm:w-4/5" : "grid-cols-2")}>{tiles}</div>
+ );
+}
+
+export function Transcript({
+ thread,
+ all,
+ skills,
+ onAnswer,
+ onOpen,
+}: {
+ thread: AssistThread;
+ all: Map<string, Generation>;
+ skills?: SkillSummary[];
+ onAnswer: (ok: boolean) => Promise<void>;
+ onOpen: (g: Generation, i: number) => void;
+}) {
+ const lastApproval = thread.items.findLast((i) => i.role === "approval")?.id;
+ const skill = (n: string) => skills?.find((s) => s.name === n);
+ return (
+ <div className="space-y-5">
+ {thread.items.map((item) => {
+ switch (item.role) {
+ case "user":
+ return (
+ <div key={item.id} className="flex animate-fade-up flex-col items-end gap-2">
+ {item.attachments?.length ? (
+ <div className="flex flex-wrap justify-end gap-1.5">
+ {item.attachments.map((a) => (
+ <div key={a} className="size-16 overflow-hidden rounded-xl border bg-muted">
+ <MediaThumb output={{ url: a, kind: /\.(mp4|webm|mov)$/i.test(a) ? "video" : /\.(mp3|wav|ogg|m4a)$/i.test(a) ? "audio" : "image" }} />
+ </div>
+ ))}
+ </div>
+ ) : null}
+ {item.skills?.length ? (
+ <div className="flex flex-wrap justify-end gap-1.5">
+ {item.skills.map((n) => (
+ <Link
+ key={n}
+ href={`/assist/skills?skill=${n}`}
+ className="inline-flex h-7 items-center gap-1.5 rounded-full bg-brand-faint pr-2.5 pl-1 text-[12px] font-medium text-brand-text hover:bg-brand-faint-hover"
+ >
+ <SkillIcon name={n} icon={skill(n)?.icon} size="sm" className="size-5" />
+ {skill(n)?.title ?? `/${n}`}
+ </Link>
+ ))}
+ </div>
+ ) : null}
+ {item.text && <div className="max-w-[85%] rounded-2xl rounded-br-md bg-secondary px-4 py-2.5 text-[15px] leading-relaxed break-words whitespace-pre-wrap">{item.text}</div>}
+ </div>
+ );
+ case "assistant":
+ return (
+ <div key={item.id} className="animate-fade-up">
+ <Prose text={item.text} />
+ </div>
+ );
+ case "tool":
+ return item.href ? (
+ <Link key={item.id} href={item.href} className="flex w-fit items-center gap-1.5 text-[12px] text-muted-foreground hover:text-foreground">
+ <Search className="size-3" /> {item.text} <ArrowUpRight className="size-3" />
+ </Link>
+ ) : (
+ <p key={item.id} className="flex items-center gap-1.5 text-[12px] text-muted-foreground">
+ <Search className="size-3" /> {item.text}
+ </p>
+ );
+ case "approval":
+ return <ApprovalCard key={item.id} item={item} live={item.id === lastApproval && thread.status === "waiting"} onAnswer={onAnswer} />;
+ case "generations":
+ return <GenerationCards key={item.id} ids={item.ids} all={all} storyboard={item.storyboard} onOpen={onOpen} />;
+ case "notice":
+ return (
+ <p key={item.id} className={cn("flex items-start gap-2 rounded-xl px-3 py-2 text-[13px]", item.tone === "error" ? "bg-destructive/10 text-destructive" : "bg-muted text-muted-foreground")}>
+ <CircleAlert className="mt-0.5 size-3.5 shrink-0" /> {item.text}
+ </p>
+ );
+ }
+ })}
+ {thread.status === "running" && (
+ <p className="shimmer-text animate-shimmer-text flex items-center gap-2 text-[14px] font-medium">
+ <Sparkles className="size-3.5" /> Thinking…
+ </p>
+ )}
+ </div>
+ );
+}
diff --git a/tests/e2e/assist-flows.mjs b/tests/e2e/assist-flows.mjs
new file mode 100644
index 00000000..68ef93f6
--- /dev/null
+++ b/tests/e2e/assist-flows.mjs
@@ -0,0 +1,189 @@
+// Assist flows in a real browser (demo mode is fine: the offline planner answers without an LLM).
+// Usage: node tests/e2e/assist-flows.mjs [appUrl] [--shots=<dir>] [--dark]
+//
+// 1. `/` opens the skill menu; picking Product Photographer shows its chip; sending starts a chat
+// with the skill loaded and an approval card that runs demo generations.
+// 2. "Remember that …" asks first, then the memory is on the Memory page.
+// 3. A project with instructions and a note source; a chat started there carries the project.
+// 4. A skill uploaded as a .zip shows up in My skills, opens, and can be deleted.
+// 5. Free / Smart / Manual: the mode picker offers Manual's models and effort.
+// 6. At 390 px the Assist sidebar opens as a sheet and the page doesn't scroll sideways.
+import { DESKTOP, launch, openRoute, PHONE } from "./_browser.mjs";
+
+const args = process.argv.slice(2);
+const app = (args.find((a) => !a.startsWith("--")) ?? "http://localhost:3000").replace(/\/$/, "");
+const shots = args.find((a) => a.startsWith("--shots="))?.slice(8);
+const scheme = args.includes("--dark") ? "dark" : "light";
+
+const failures = [];
+const step = async (name, fn) => {
+ try {
+ await fn();
+ console.log(`ok ${name}`);
+ } catch (e) {
+ console.log(`FAIL ${name}: ${e.message.split("\n")[0]}`);
+ failures.push(name);
+ }
+};
+const shot = async (page, name) => shots && page.screenshot({ path: `${shots}/${name}-${scheme}.png` });
+
+/** A stored ZIP with one skill folder (no compression, so no dependency). */
+function skillZip(name) {
+ const md = Buffer.from(`---\nname: ${name}\ntitle: E2E Recipe Reels\ndescription: Turns a recipe into a short vertical cooking reel.\nwhen_to_use: The user shares a recipe.\n---\n\n# Recipe reels\n\n1. Write a 30-second script.\n2. Make 3 vertical shots.\n`);
+ const notes = Buffer.from("Keep it under 30 seconds.\n");
+ const files = [
+ { name: `${name}/SKILL.md`, data: md },
+ { name: `${name}/notes.md`, data: notes },
+ ];
+ const table = Array.from({ length: 256 }, (_, n) => {
+ let c = n;
+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
+ return c >>> 0;
+ });
+ const crc = (b) => {
+ let c = 0xffffffff;
+ for (const x of b) c = table[(c ^ x) & 0xff] ^ (c >>> 8);
+ return (c ^ 0xffffffff) >>> 0;
+ };
+ const parts = [];
+ const dir = [];
+ let off = 0;
+ for (const f of files) {
+ const n = Buffer.from(f.name);
+ const h = Buffer.alloc(30);
+ h.writeUInt32LE(0x04034b50, 0);
+ h.writeUInt16LE(20, 4);
+ h.writeUInt32LE(crc(f.data), 14);
+ h.writeUInt32LE(f.data.length, 18);
+ h.writeUInt32LE(f.data.length, 22);
+ h.writeUInt16LE(n.length, 26);
+ const c = Buffer.alloc(46);
+ c.writeUInt32LE(0x02014b50, 0);
+ c.writeUInt16LE(20, 4);
+ c.writeUInt16LE(20, 6);
+ c.writeUInt32LE(crc(f.data), 16);
+ c.writeUInt32LE(f.data.length, 20);
+ c.writeUInt32LE(f.data.length, 24);
+ c.writeUInt16LE(n.length, 28);
+ c.writeUInt32LE(off, 42);
+ parts.push(h, n, f.data);
+ dir.push(c, n);
+ off += 30 + n.length + f.data.length;
+ }
+ const d = Buffer.concat(dir);
+ const e = Buffer.alloc(22);
+ e.writeUInt32LE(0x06054b50, 0);
+ e.writeUInt16LE(files.length, 8);
+ e.writeUInt16LE(files.length, 10);
+ e.writeUInt32LE(d.length, 12);
+ e.writeUInt32LE(off, 16);
+ return Buffer.concat([...parts, d, e]);
+}
+
+const browser = await launch();
+const errors = [];
+const ctx = await browser.newContext({ ...DESKTOP, colorScheme: scheme });
+const page = await ctx.newPage();
+page.on("pageerror", (e) => errors.push(e.message));
+
+await step("skill menu, chip and a chat with the skill loaded", async () => {
+ await openRoute(page, `${app}/assist`);
+ const box = page.getByRole("combobox", { name: "Message" });
+ await box.click();
+ await box.type("/prod");
+ await page.getByRole("option", { name: /Product Photographer/ }).waitFor({ timeout: 10_000 });
+ await shot(page, "flow-skill-menu");
+ await box.press("Enter");
+ await page.getByText("Product Photographer", { exact: true }).first().waitFor();
+ await box.type("a matte black perfume bottle on travertine");
+ await box.press("Enter");
+ await page.waitForURL(/\/assist\?c=/, { timeout: 20_000 });
+ await page.getByRole("button", { name: /^Run/ }).waitFor({ timeout: 30_000 });
+ await shot(page, "flow-approval");
+ await page.getByRole("button", { name: /^Run/ }).click();
+ await page.getByText(/On it — the results will appear here/).waitFor({ timeout: 30_000 });
+ await page.getByRole("button", { name: /^Open / }).first().waitFor({ timeout: 60_000 });
+ await shot(page, "flow-results");
+});
+
+await step("remember asks first, then shows on the Memory page", async () => {
+ await openRoute(page, `${app}/assist`);
+ const box = page.getByRole("combobox", { name: "Message" });
+ await box.fill("Remember that I always want vertical 9:16 videos");
+ await box.press("Enter");
+ await page.getByText("Remember this?").waitFor({ timeout: 30_000 });
+ await shot(page, "flow-remember");
+ await page.getByRole("button", { name: "Remember", exact: true }).click();
+ await page.getByText(/Saved to memory/).waitFor({ timeout: 30_000 });
+ await openRoute(page, `${app}/assist/memory`);
+ await page.getByText("I always want vertical 9:16 videos.").waitFor({ timeout: 15_000 });
+ await shot(page, "flow-memory");
+});
+
+await step("a project with instructions and a note; its chats carry it", async () => {
+ await openRoute(page, `${app}/assist/skills`);
+ await page.getByRole("button", { name: "New project" }).first().click();
+ await page.getByLabel("Name").fill("E2E Spring campaign");
+ await page.getByLabel("Instructions").fill("Everything is for a spring sneaker drop: pastel palette, 9:16.");
+ await page.getByRole("button", { name: "Create project" }).click();
+ await page.waitForURL(/\/assist\/projects\//, { timeout: 15_000 });
+ await page.getByRole("heading", { name: /What are we creating in E2E Spring campaign/ }).waitFor();
+ await page.getByRole("tab", { name: /Sources/ }).click();
+ await page.getByRole("button", { name: "Note" }).click();
+ await page.getByLabel("Title").fill("Brand voice");
+ await page.getByLabel("Text").fill("Playful, short sentences, no jargon.");
+ await page.getByRole("button", { name: "Add note" }).click();
+ await page.getByText("Brand voice").first().waitFor({ timeout: 10_000 });
+ await shot(page, "flow-project");
+ const box = page.getByRole("combobox", { name: "Message" });
+ await box.fill("Three sneaker stills on pastel backdrops");
+ await box.press("Enter");
+ await page.waitForURL(/\/assist\?c=/, { timeout: 20_000 });
+ await page.getByRole("link", { name: /E2E Spring campaign/ }).first().waitFor({ timeout: 15_000 });
+});
+
+await step("upload a .zip skill, open it, delete it", async () => {
+ const name = `e2e-recipe-${Date.now().toString(36)}`;
+ await openRoute(page, `${app}/assist/skills`);
+ await page.locator('input[type="file"]').setInputFiles({ name: `${name}.zip`, mimeType: "application/zip", buffer: skillZip(name) });
+ await page.getByRole("tab", { name: /My skills/ }).waitFor();
+ await page.getByText("E2E Recipe Reels").first().waitFor({ timeout: 15_000 });
+ await page.getByRole("button", { name: "E2E Recipe Reels" }).click();
+ await page.getByRole("dialog").getByText("notes.md").waitFor();
+ await shot(page, "flow-skill-detail");
+ await page.getByRole("dialog").getByRole("button", { name: "Delete" }).click();
+ await page.getByRole("alertdialog").getByRole("button", { name: "Delete" }).click();
+ await page.getByText("No skills of your own yet").waitFor({ timeout: 10_000 });
+});
+
+await step("mode picker offers Manual with models and effort", async () => {
+ await openRoute(page, `${app}/assist`);
+ await page.getByRole("button", { name: /^Mode:/ }).click();
+ await page.getByRole("radio", { name: "Manual" }).click();
+ await page.getByRole("radio", { name: /Offline planner/ }).waitFor();
+ await shot(page, "flow-mode");
+ await page.keyboard.press("Escape");
+});
+
+await ctx.close();
+
+await step("phone: the sidebar opens as a sheet; no sideways scroll", async () => {
+ const phone = await browser.newContext({ ...PHONE, colorScheme: scheme });
+ const p = await phone.newPage();
+ p.on("pageerror", (e) => errors.push(e.message));
+ for (const r of ["/assist", "/assist/skills", "/assist/memory"]) {
+ await openRoute(p, app + r);
+ const wide = await p.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
+ if (wide > 0) throw new Error(`${r} is ${wide}px too wide`);
+ }
+ await openRoute(p, `${app}/assist`);
+ await p.getByRole("button", { name: "Chats, projects, skills and memory" }).click();
+ await p.getByRole("dialog").getByRole("link", { name: "Skills" }).waitFor();
+ await shot(p, "flow-phone-rail");
+ await phone.close();
+});
+
+await browser.close();
+if (errors.length) console.log(`page errors:\n${errors.join("\n")}`);
+console.log(failures.length ? `${failures.length} failed: ${failures.join("; ")}` : "All Assist flows passed.");
+process.exit(failures.length || errors.length ? 1 : 0);