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: mode picker applies on close, chat menu (rename, move to project), project Assets tab, hydration-safe lists

Claudeee87bd14c998
diff --git a/src/app/api/assist/projects/[projectId]/assets/route.ts b/src/app/api/assist/projects/[projectId]/assets/route.ts
new file mode 100644
index 00000000..35efacf7
--- /dev/null
+++ b/src/app/api/assist/projects/[projectId]/assets/route.ts
@@ -0,0 +1,11 @@
+import { connection } from "next/server";
+import { projectAssets } from "@/server/assist/agent";
+import { getProject } from "@/server/assist/projects";
+
+/** The project's assets: what its chats made (finished generations, newest first). */
+export async function GET(_req: Request, ctx: RouteContext<"/api/assist/projects/[projectId]/assets">) {
+ await connection();
+ const { projectId } = await ctx.params;
+ if (!getProject(projectId)) return Response.json({ error: "Not found" }, { status: 404 });
+ return Response.json({ items: projectAssets(projectId) });
+}
diff --git a/src/components/assist-view.tsx b/src/components/assist-view.tsx
index b44a1f33..0c3c7f16 100644
--- a/src/components/assist-view.tsx
+++ b/src/components/assist-view.tsx
@@ -12,6 +12,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip
import { EngineSwitch } from "@/components/studio/engine-switch";
import { Viewer } from "@/components/studio/viewer";
import { AssistComposer } from "@/components/assist/composer";
+import { ChatMenu } from "@/components/assist/chat-menu";
import { useChatActions, useChats, useProjects, useSkills } from "@/components/assist/hooks";
import { ModePicker, useModeChoice } from "@/components/assist/mode-picker";
import { ProjectDot, RailButton } from "@/components/assist/shell";
@@ -168,6 +169,7 @@ export function AssistView() {
<MessageSquarePlus /> <span className="hidden sm:inline">New chat</span>
</Button>
)}
+ {thread && <ChatMenu chat={thread} onDeleted={() => go(null)} />}
</div>
</header>
@@ -234,6 +236,7 @@ export function AssistView() {
value={{ mode: thread.mode ?? "smart", agent: thread.agent, model: thread.model, effort: thread.effort }}
availability={can}
disabled={thread.status === "running"}
+ applyOnClose
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)} />
diff --git a/src/components/assist/chat-menu.tsx b/src/components/assist/chat-menu.tsx
new file mode 100644
index 00000000..10e1f07d
--- /dev/null
+++ b/src/components/assist/chat-menu.tsx
@@ -0,0 +1,171 @@
+"use client";
+
+import { Check, FolderInput, MoreHorizontal, Pencil, Trash2 } from "lucide-react";
+import { useId, useState } from "react";
+import { toast } from "sonner";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@/components/ui/alert-dialog";
+import { Button } from "@/components/ui/button";
+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import type { AssistThreadSummary } from "@/lib/assist";
+import { cn } from "@/lib/utils";
+import { useChatActions, useProjects } from "./hooks";
+import { ProjectDot } from "./project-dot";
+
+/**
+ * A chat's menu (the rail row and the chat header): rename it, move it into a project or out of
+ * one, delete it. While a reply is running the server refuses a move, and says so in a toast.
+ */
+export function ChatMenu({
+ chat,
+ onDeleted,
+ className,
+ align = "end",
+}: {
+ chat: Pick<AssistThreadSummary, "id" | "title" | "projectId" | "status">;
+ onDeleted?: () => void;
+ className?: string;
+ align?: "start" | "end";
+}) {
+ const projects = useProjects();
+ const actions = useChatActions();
+ const [renaming, setRenaming] = useState(false);
+ const [deleting, setDeleting] = useState(false);
+ const move = async (projectId: string | null) => {
+ if ((chat.projectId ?? null) === projectId) return;
+ try {
+ await actions.patch(chat.id, { projectId });
+ const p = projects.data?.find((x) => x.id === projectId);
+ toast(p ? `Moved to ${p.name}` : "Moved out of the project", { duration: 1500 });
+ } catch (e) {
+ toast.error((e as Error).message);
+ }
+ };
+ const remove = async () => {
+ try {
+ await actions.remove(chat.id);
+ onDeleted?.();
+ toast("Chat deleted", { duration: 1500 });
+ } catch (e) {
+ toast.error((e as Error).message);
+ }
+ };
+ return (
+ <>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="ghost" size="icon-sm" className={cn("text-muted-foreground", className)} aria-label={`More for ${chat.title}`}>
+ <MoreHorizontal />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align={align} className="w-52">
+ <DropdownMenuItem onSelect={() => setRenaming(true)}>
+ <Pencil /> Rename…
+ </DropdownMenuItem>
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <FolderInput /> Move to project
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="max-h-72 w-52 overflow-y-auto">
+ <DropdownMenuItem onSelect={() => void move(null)}>
+ <span className="size-2.5 shrink-0 rounded-full border border-dashed border-muted-foreground" aria-hidden />
+ <span className="flex-1">No project</span>
+ {!chat.projectId && <Check className="text-brand-text" aria-label="Current" />}
+ </DropdownMenuItem>
+ {projects.data?.length ? <DropdownMenuSeparator /> : null}
+ {projects.data?.map((p) => (
+ <DropdownMenuItem key={p.id} onSelect={() => void move(p.id)}>
+ <ProjectDot project={p} />
+ <span className="min-w-0 flex-1 truncate">{p.name}</span>
+ {chat.projectId === p.id && <Check className="text-brand-text" aria-label="Current" />}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem variant="destructive" onSelect={() => setDeleting(true)}>
+ <Trash2 /> Delete…
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <Dialog open={renaming} onOpenChange={setRenaming}>
+ <DialogContent className="sm:max-w-[420px]">{renaming && <RenameForm chat={chat} onDone={() => setRenaming(false)} />}</DialogContent>
+ </Dialog>
+ <AlertDialog open={deleting} onOpenChange={setDeleting}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Delete this chat?</AlertDialogTitle>
+ <AlertDialogDescription>“{chat.title}” and its messages are removed. Everything it made stays in your Library.</AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction variant="destructive" onClick={() => void remove()}>
+ Delete
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </>
+ );
+}
+
+function RenameForm({ chat, onDone }: { chat: Pick<AssistThreadSummary, "id" | "title">; onDone: () => void }) {
+ const actions = useChatActions();
+ const id = useId();
+ const [title, setTitle] = useState(chat.title);
+ const [busy, setBusy] = useState(false);
+ const save = async (e: React.FormEvent) => {
+ e.preventDefault();
+ const t = title.trim();
+ if (!t || t === chat.title) return onDone();
+ setBusy(true);
+ try {
+ await actions.patch(chat.id, { title: t });
+ 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">Rename chat</DialogTitle>
+ <DialogDescription className="sr-only">Give this chat a new name.</DialogDescription>
+ </DialogHeader>
+ <div className="space-y-2">
+ <Label htmlFor={id}>Name</Label>
+ <Input id={id} value={title} onChange={(e) => setTitle(e.target.value)} maxLength={80} autoFocus onFocus={(e) => e.currentTarget.select()} />
+ </div>
+ <DialogFooter>
+ <Button type="button" variant="ghost" onClick={onDone}>
+ Cancel
+ </Button>
+ <Button type="submit" disabled={busy || !title.trim()}>
+ Save
+ </Button>
+ </DialogFooter>
+ </form>
+ );
+}
diff --git a/src/components/assist/hooks.ts b/src/components/assist/hooks.ts
index 5182c58b..c9fc5a1d 100644
--- a/src/components/assist/hooks.ts
+++ b/src/components/assist/hooks.ts
@@ -1,6 +1,7 @@
"use client";
-import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { useQuery, useQueryClient, type UseQueryResult } from "@tanstack/react-query";
+import { useHydrated } from "@/lib/api";
import type {
AssistAvailability,
AssistMemory,
@@ -16,7 +17,7 @@ import type {
Skill,
SkillSummary,
} from "@/lib/assist";
-import type { Engine } from "@/lib/catalog/types";
+import type { Engine, Generation } from "@/lib/catalog/types";
/**
* React Query hooks for Assist's skills, memory, projects and chat lists (/api/assist/**).
@@ -31,6 +32,16 @@ async function json<T>(res: Response): Promise<T> {
return body;
}
+/**
+ * Until the page has hydrated, a query reads as loading: the first client render then matches the
+ * server's HTML even when another Suspense boundary already filled the cache with the same key.
+ */
+function useHydrationSafe<T extends UseQueryResult<unknown, Error>>(q: T): T {
+ const hydrated = useHydrated();
+ if (hydrated) return q;
+ return { ...q, data: undefined, error: null, status: "pending", isPending: true, isLoading: true, isFetching: true, isSuccess: false, isError: false, fetchStatus: "fetching" } as T;
+}
+
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) }));
@@ -48,11 +59,13 @@ 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,
- });
+ return useHydrationSafe(
+ 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() {
@@ -88,19 +101,23 @@ export function useChatActions() {
// Skills
export function useSkills() {
- return useQuery({
- queryKey: ["assist-skills"],
- queryFn: async () => (await json<{ items: SkillSummary[] }>(await fetch("/api/assist/skills"))).items,
- staleTime: 30_000,
- });
+ return useHydrationSafe(
+ 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}`)),
- });
+ return useHydrationSafe(
+ useQuery({
+ queryKey: ["assist-skills", name],
+ enabled: !!name,
+ queryFn: async () => json<Skill>(await fetch(`/api/assist/skills/${name}`)),
+ }),
+ );
}
export interface SkillForm {
@@ -160,10 +177,12 @@ export function useSkillActions() {
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,
- });
+ return useHydrationSafe(
+ 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() {
@@ -196,20 +215,42 @@ export function useMemoryActions() {
// Projects
export function useProjects() {
- return useQuery({
- queryKey: ["assist-projects"],
- queryFn: async () => (await json<{ items: AssistProject[] }>(await fetch("/api/assist/projects"))).items,
- staleTime: 10_000,
- });
+ return useHydrationSafe(
+ 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,
- });
+ return useHydrationSafe(
+ 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 ProjectAsset {
+ generation: Generation;
+ chatId: string;
+ chatTitle: string;
+}
+
+/** What a project's chats made (the Assets tab), refreshed when the tab is opened again. */
+export function useProjectAssets(id: string, enabled = true) {
+ return useHydrationSafe(
+ useQuery({
+ queryKey: ["assist-projects", id, "assets"],
+ enabled,
+ queryFn: async () => (await json<{ items: ProjectAsset[] }>(await fetch(`/api/assist/projects/${id}/assets`))).items,
+ staleTime: 10_000,
+ }),
+ );
}
export interface ProjectForm {
diff --git a/src/components/assist/mode-picker.tsx b/src/components/assist/mode-picker.tsx
index 2baf5b5c..3393a425 100644
--- a/src/components/assist/mode-picker.tsx
+++ b/src/components/assist/mode-picker.tsx
@@ -15,6 +15,7 @@ import {
type AssistModeChoice,
} from "@/lib/assist";
import { cn } from "@/lib/utils";
+import { radioKeys, radioTab } from "@/components/studio/radio-keys";
const KEY = "fuobe:assist-mode";
@@ -74,24 +75,96 @@ export function modeChipLabel(c: AssistModeChoice | null, can?: AssistAvailabili
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 sameChoice = (a: AssistModeChoice | null, b: AssistModeChoice | null) =>
+ (a?.mode ?? null) === (b?.mode ?? null) && (a?.agent ?? null) === (b?.agent ?? null) && (a?.model ?? null) === (b?.model ?? null) && (a?.effort ?? null) === (b?.effort ?? null);
+
+interface ModelOption {
+ key: string;
+ on: boolean;
+ disabled?: boolean;
+ pick: Partial<AssistModeChoice>;
+ icon: typeof Bot;
+ title: React.ReactNode;
+ hint: string;
+}
+
+/**
+ * Supercomputer's Free / Smart / Manual, on Fuobe's agents (Claude, Ollama, the offline planner).
+ * With `applyOnClose` (an existing chat) choices are kept in the menu and sent once when it
+ * closes, so trying the tabs doesn't switch the chat at every click. Smart needs Claude: without
+ * an Anthropic key it can't be picked (and a saved Smart shows as the Free it runs as).
+ */
+export function ModePicker({
+ value,
+ onChange,
+ availability: can,
+ disabled,
+ applyOnClose,
+}: {
+ value: AssistModeChoice | null;
+ onChange: (c: AssistModeChoice) => void;
+ availability?: AssistAvailability;
+ disabled?: boolean;
+ applyOnClose?: boolean;
+}) {
const [open, setOpen] = useState(false);
- const mode = value?.mode ?? can?.defaultMode ?? "smart";
+ const [draft, setDraft] = useState<AssistModeChoice | null>(null);
+ const shown = (applyOnClose && open ? draft : null) ?? value;
+ const smartOff = !!can && !can.claude;
+ const picked = shown?.mode ?? can?.defaultMode ?? "smart";
+ const mode = picked === "smart" && smartOff ? "free" : picked;
+ // The label, its aria-label and the icon all come from this one resolved value.
+ const resolved: AssistModeChoice = { ...(shown ?? {}), mode };
+ const label = modeChipLabel(resolved, can);
const Icon = MODE_ICON[mode];
- const agent: AssistAgent = value?.agent ?? "claude";
- const set = (patch: Partial<AssistModeChoice>) => onChange({ ...(value ?? { mode }), ...patch } as AssistModeChoice);
+ const agent: AssistAgent = shown?.agent ?? "claude";
+ const set = (patch: Partial<AssistModeChoice>) => {
+ const next = { ...resolved, ...patch } as AssistModeChoice;
+ if (applyOnClose) setDraft(next);
+ else onChange(next);
+ };
+ const onOpenChange = (o: boolean) => {
+ if (o) setDraft(value);
+ else if (applyOnClose && draft && !sameChoice(draft, value)) onChange(draft);
+ setOpen(o);
+ };
+ const pending = applyOnClose && open && draft && !sameChoice(draft, value);
+
+ const models: ModelOption[] = [
+ ...CLAUDE_MODELS.map((m) => ({
+ key: m.id,
+ on: agent === "claude" && (shown?.model ?? DEFAULT_CLAUDE_MODEL) === m.id,
+ disabled: !can?.claude,
+ pick: { agent: "claude" as const, model: m.id },
+ icon: Bot,
+ title: <span className="block text-[13px] font-medium">{m.label}</span>,
+ hint: m.hint,
+ })),
+ ...(can?.ollamaModels.length ? can.ollamaModels : can?.ollama ? [can.ollamaModel] : []).map((name) => ({
+ key: `ollama:${name}`,
+ on: agent === "ollama" && (shown?.model ?? can?.ollamaModel) === name,
+ pick: { agent: "ollama" as const, model: name, effort: null },
+ icon: Cpu,
+ title: <span className="block truncate font-mono text-[12px]">{name}</span>,
+ hint: "Local, through Ollama · free",
+ })),
+ { key: "offline", on: agent === "offline", pick: { agent: "offline", model: null, effort: null }, icon: Gauge, title: <span className="block text-[13px] font-medium">Offline planner</span>, hint: "Rules, no LLM — simple requests only" },
+ ];
+ // One Tab stop per group: the picked option, or the first one that can be picked.
+ const modelStop = models.find((m) => m.on && !m.disabled)?.key ?? models.find((m) => !m.disabled)?.key;
+ const effort = shown?.effort ?? DEFAULT_EFFORT;
+
return (
- <Popover open={open} onOpenChange={setOpen}>
+ <Popover open={open} onOpenChange={onOpenChange}>
<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)}`}
+ aria-label={`Mode: ${label}`}
>
<Icon className="size-3.5 shrink-0" />
- <span className="truncate">{modeChipLabel(value ?? { mode }, can)}</span>
+ <span className="truncate">{label}</span>
<ChevronDown className="size-3 shrink-0 opacity-60" />
</button>
</PopoverTrigger>
@@ -105,28 +178,34 @@ export function ModePicker({ value, onChange, availability: can, disabled }: { v
, 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 role="radiogroup" aria-label="Mode" onKeyDown={radioKeys} className="grid grid-cols-3 gap-1 rounded-full bg-muted p-0.5">
+ {ASSIST_MODES.map((m) => {
+ const off = m.id === "smart" && smartOff;
+ return (
+ <button
+ key={m.id}
+ type="button"
+ role="radio"
+ aria-checked={mode === m.id}
+ tabIndex={radioTab(mode === m.id)}
+ disabled={off}
+ title={off ? "Needs an Anthropic API key (Settings)" : undefined}
+ onClick={() => set({ mode: m.id, ...(m.id === "manual" && !shown?.agent && { agent: can?.claude ? "claude" : can?.ollama ? "ollama" : "offline" }) })}
+ className={cn("h-8 rounded-full text-[13px] font-medium transition-colors disabled:opacity-45", mode === m.id ? "bg-background text-foreground shadow-soft" : "text-muted-foreground enabled: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 && (
+ {smartOff && (
<p className="mt-2 px-1 text-[12px] text-warning">
- Needs an Anthropic API key —{" "}
+ Smart and the Claude models need 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" && (
@@ -142,81 +221,39 @@ export function ModePicker({ value, onChange, availability: can, disabled }: { v
)}
{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 role="radiogroup" aria-label="Model" onKeyDown={radioKeys} className="space-y-1">
+ {models.map((m) => (
+ <button
+ key={m.key}
+ type="button"
+ role="radio"
+ aria-checked={m.on}
+ tabIndex={m.key === modelStop ? 0 : -1}
+ disabled={m.disabled}
+ onClick={() => set(m.pick)}
+ 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", m.on && "bg-brand-faint hover:bg-brand-faint-hover")}
+ >
+ <m.icon className="size-4 shrink-0 text-muted-foreground" />
+ <span className="min-w-0 flex-1">
+ {m.title}
+ <span className="block text-[11px] text-muted-foreground">{m.hint}</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">
+ <div role="radiogroup" aria-label="Effort" onKeyDown={radioKeys} 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}
+ aria-checked={effort === e.id}
+ tabIndex={radioTab(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")}
+ className={cn("h-7 rounded-full text-[12px] font-medium transition-colors", effort === e.id ? "bg-background text-foreground shadow-soft" : "text-muted-foreground hover:text-foreground")}
>
{e.label}
</button>
@@ -227,6 +264,7 @@ export function ModePicker({ value, onChange, availability: can, disabled }: { v
)}
</div>
)}
+ {pending && <p className="mt-3 border-t px-1 pt-2 text-[11px] text-muted-foreground">Applies to this chat when you close this menu.</p>}
</PopoverContent>
</Popover>
);
diff --git a/src/components/assist/project-dialog.tsx b/src/components/assist/project-dialog.tsx
index 088f04a1..c68e97e8 100644
--- a/src/components/assist/project-dialog.tsx
+++ b/src/components/assist/project-dialog.tsx
@@ -10,8 +10,9 @@ 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 { PROJECT_COLORS, PROJECT_LIMITS, PROJECT_SWATCH, type AssistProject, type ProjectColor } from "@/lib/assist";
import { cn } from "@/lib/utils";
+import { radioKeys, radioTab } from "@/components/studio/radio-keys";
import { useProjectActions, useSkills } from "./hooks";
import { SkillIcon } from "./skill-icon";
@@ -78,7 +79,7 @@ function Form({ project, onDone }: { project?: AssistProject; onDone: (p?: Assis
<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">
+ <div role="radiogroup" aria-label="Colour" onKeyDown={radioKeys} className="flex flex-wrap gap-2 pt-1">
{PROJECT_COLORS.map((c) => (
<button
key={c}
@@ -86,9 +87,10 @@ function Form({ project, onDone }: { project?: AssistProject; onDone: (p?: Assis
role="radio"
aria-checked={color === c}
aria-label={c}
+ tabIndex={radioTab(color === 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}
+ className={cn("grid size-7 place-items-center rounded-full ring-offset-2 ring-offset-background transition", color === c && "ring-2 ring-primary")}
+ style={{ backgroundColor: PROJECT_SWATCH[c] }}
>
{color === c && <Check className="size-3.5 text-white" />}
</button>
diff --git a/src/components/assist/project-dot.tsx b/src/components/assist/project-dot.tsx
new file mode 100644
index 00000000..40dbb7c5
--- /dev/null
+++ b/src/components/assist/project-dot.tsx
@@ -0,0 +1,7 @@
+import { PROJECT_SWATCH, type AssistProject } from "@/lib/assist";
+import { cn } from "@/lib/utils";
+
+/** A project's colour dot (sidebar rows, pickers, breadcrumbs). */
+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", className)} style={{ backgroundColor: PROJECT_SWATCH[project.color] }} />;
+}
diff --git a/src/components/assist/project-view.tsx b/src/components/assist/project-view.tsx
index 3f7b765d..ce274e6e 100644
--- a/src/components/assist/project-view.tsx
+++ b/src/components/assist/project-view.tsx
@@ -20,7 +20,7 @@ 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 { ErrorState, NotFoundState } from "@/components/empty-state";
import {
AlertDialog,
AlertDialogAction,
@@ -41,13 +41,16 @@ 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 { MediaThumb } from "@/components/studio/feed";
+import { Viewer } from "@/components/studio/viewer";
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 { ChatMenu } from "./chat-menu";
+import { useChatActions, useChats, useProject, useProjectActions, useProjectAssets, useSkills } from "./hooks";
import { MemoryView } from "./memory-view";
import { useModeChoice } from "./mode-picker";
import { ProjectDialog } from "./project-dialog";
@@ -65,7 +68,11 @@ export function ProjectView({ id }: { id: string }) {
<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>;
+ if (!project.data) {
+ const status = (project.error as { status?: number } | null)?.status;
+ if (project.error && status !== 404) return <ErrorState error={project.error} retry={() => void project.refetch()} />;
+ 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} />;
}
@@ -83,6 +90,7 @@ function Project({ p }: { p: AssistProject }) {
const [settings, setSettings] = useState(false);
const [confirm, setConfirm] = useState(false);
const [draft, setDraft] = useState({ key: 0, text: "" });
+ const [tab, setTab] = useState("chats");
return (
<div className="flex min-h-svh min-w-0 flex-col">
@@ -131,11 +139,14 @@ function Project({ p }: { p: AssistProject }) {
{!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">
+ <Tabs value={tab} onValueChange={setTab} 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="assets" className="px-3">
+ Assets
+ </TabsTrigger>
<TabsTrigger value="sources" className="px-3">
Sources <span className="font-mono text-[11px] text-muted-foreground">{p.sources.length || ""}</span>
</TabsTrigger>
@@ -149,11 +160,12 @@ function Project({ p }: { p: AssistProject }) {
) : 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">
+ <li key={t.id} className="relative">
+ <Link href={`/assist?c=${t.id}`} className="flex items-center gap-3 py-3 pr-12 pl-4 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>
+ <ChatMenu chat={t} className="absolute top-1/2 right-2 -translate-y-1/2" />
</li>
))}
</ul>
@@ -161,6 +173,9 @@ function Project({ p }: { p: AssistProject }) {
<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="assets">
+ <Assets p={p} active={tab === "assets"} />
+ </TabsContent>
<TabsContent value="sources">
<Sources p={p} />
</TabsContent>
@@ -199,6 +214,51 @@ function Project({ p }: { p: AssistProject }) {
);
}
+/** What the project's chats made: their finished results, newest first, opening in the viewer. */
+function Assets({ p, active }: { p: AssistProject; active: boolean }) {
+ const assets = useProjectAssets(p.id, active);
+ const [open, setOpen] = useState<{ at: number; i: number } | null>(null);
+ const list = assets.data ?? [];
+ const tiles = list.flatMap((a, at) => a.generation.outputs.map((o, i) => ({ a, at, o, i })));
+ if (assets.isLoading)
+ return (
+ <div className="grid grid-cols-3 gap-2 sm:grid-cols-4">
+ {Array.from({ length: 8 }, (_, i) => (
+ <Skeleton key={i} className="aspect-square rounded-xl" />
+ ))}
+ </div>
+ );
+ if (assets.isError) return <p className="rounded-2xl border border-dashed px-4 py-8 text-center text-[13px] text-muted-foreground">Couldn&apos;t load the assets: {(assets.error as Error).message}</p>;
+ if (!tiles.length) return <p className="rounded-2xl border border-dashed px-4 py-8 text-center text-[13px] text-muted-foreground">Nothing made here yet — what this project&apos;s chats create shows up here.</p>;
+ const cur = open ? list[open.at] : null;
+ return (
+ <>
+ <p className="mb-3 text-[13px] text-muted-foreground">
+ {tiles.length} result{tiles.length === 1 ? "" : "s"} from this project&apos;s chats. Everything is in your Library too.
+ </p>
+ <ul className="grid grid-cols-3 gap-2 sm:grid-cols-4">
+ {tiles.map(({ a, at, o, i }) => (
+ <li key={`${a.generation.id}-${i}`}>
+ <button onClick={() => setOpen({ at, i })} className="group relative block aspect-square w-full overflow-hidden rounded-xl bg-muted" aria-label={`Open ${a.generation.request.prompt?.slice(0, 60) || "result"} (from ${a.chatTitle})`}>
+ <MediaThumb output={o} g={a.generation} className="transition duration-300 group-hover:scale-[1.03]" />
+ {a.generation.provider === "mock" && <span className="absolute top-1.5 right-1.5 rounded-full bg-background/80 px-1.5 py-0.5 text-[10px] font-medium">Demo</span>}
+ </button>
+ </li>
+ ))}
+ </ul>
+ {open && cur && (
+ <Viewer
+ generation={cur.generation}
+ index={open.i}
+ onClose={() => setOpen(null)}
+ onPrev={open.at > 0 ? () => setOpen({ at: open.at - 1, i: 0 }) : undefined}
+ onNext={open.at < list.length - 1 ? () => setOpen({ at: open.at + 1, i: 0 }) : undefined}
+ />
+ )}
+ </>
+ );
+}
+
function Sources({ p }: { p: AssistProject }) {
const actions = useProjectActions();
const elements = useElements();
diff --git a/src/components/assist/shell.tsx b/src/components/assist/shell.tsx
index a8b9c798..8ac9e0a0 100644
--- a/src/components/assist/shell.tsx
+++ b/src/components/assist/shell.tsx
@@ -1,30 +1,20 @@
"use client";
-import { Brain, FolderPlus, MessageSquarePlus, MessagesSquare, Search, Sparkles, Trash2, X } from "lucide-react";
+import { Brain, FolderPlus, MessageSquarePlus, MessagesSquare, Search, Sparkles, X } from "lucide-react";
import Link from "next/link";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { Suspense, useDeferredValue, useState } from "react";
-import { 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 { ChatMenu } from "./chat-menu";
+import { useChats, useProjects } from "./hooks";
import { ProjectDialog } from "./project-dialog";
+import { ProjectDot } from "./project-dot";
/**
* Assist's own sidebar (Supercomputer's): New chat, Search, Skills, Memory, Projects and Chats.
@@ -58,7 +48,7 @@ export function RailButton({ className }: { className?: string }) {
<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}>
+ <SheetContent side="left" className="w-[min(86vw,320px)] gap-0 p-0" aria-describedby={undefined} onOpenAutoFocus={(e) => e.preventDefault()}>
<SheetTitle className="sr-only">Assist</SheetTitle>
<SheetDescription className="sr-only">Chats, projects, skills and memory</SheetDescription>
<Suspense fallback={<RailSkeleton />}>
@@ -95,9 +85,7 @@ function RailLink({ href, icon: Icon, label, active, onNavigate }: { href: strin
);
}
-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} />;
-}
+export { ProjectDot };
function Rail({ onNavigate }: { onNavigate?: () => void }) {
const pathname = usePathname() ?? "";
@@ -108,23 +96,11 @@ function Rail({ onNavigate }: { onNavigate?: () => void }) {
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">
+ <div className={cn("space-y-2 p-3 pb-2", onNavigate && "pt-12")}>
<Button asChild variant="outline" className="h-9 w-full justify-start rounded-full">
<Link href="/assist" onClick={onNavigate}>
<MessageSquarePlus /> New chat
@@ -220,13 +196,11 @@ function Rail({ onNavigate }: { onNavigate?: () => void }) {
</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>
+ <ChatMenu
+ chat={t}
+ onDeleted={() => t.id === current && router.replace("/assist", { scroll: false })}
+ className="absolute top-1/2 right-1 size-7 -translate-y-1/2 opacity-100 focus-visible:opacity-100 data-[state=open]:opacity-100 sm:opacity-0 sm:group-hover/chat:opacity-100"
+ />
</li>
);
})}
@@ -236,20 +210,6 @@ function Rail({ onNavigate }: { onNavigate?: () => void }) {
)}
</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}
diff --git a/src/components/assist/skills-view.tsx b/src/components/assist/skills-view.tsx
index 04d0564a..850845bf 100644
--- a/src/components/assist/skills-view.tsx
+++ b/src/components/assist/skills-view.tsx
@@ -29,6 +29,7 @@ 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 { radioKeys } from "@/components/studio/radio-keys";
import { useSkill, useSkillActions, useSkills, type SkillForm } from "./hooks";
import { RailButton } from "./shell";
import { SKILL_ICONS, SkillIcon } from "./skill-icon";
@@ -463,9 +464,19 @@ function EditorForm({ skill, onClose, onSaved }: { skill: Skill | null; onClose:
</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")}>
+ <div role="radiogroup" aria-label="Icon" onKeyDown={radioKeys} className="flex flex-wrap gap-1.5">
+ {ICON_CHOICES.map((i, k) => (
+ <button
+ key={i}
+ type="button"
+ role="radio"
+ aria-checked={form.icon === i}
+ aria-label={i}
+ // One Tab stop: the picked icon, or the first while none is picked.
+ tabIndex={form.icon === i || (k === 0 && !ICON_CHOICES.some((c) => c === form.icon)) ? 0 : -1}
+ 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>
))}
diff --git a/src/lib/assist.ts b/src/lib/assist.ts
index 6d242dfd..b6c28623 100644
--- a/src/lib/assist.ts
+++ b/src/lib/assist.ts
@@ -536,6 +536,10 @@ export const PROJECT_COLORS = ["iris", "sky", "teal", "lime", "amber", "rose", "
export type ProjectColor = (typeof PROJECT_COLORS)[number];
/** Hues for the project swatches (oklch), matching the Library's folder colours. */
export const PROJECT_HUE: Record<ProjectColor, number> = { iris: 280, sky: 230, teal: 185, lime: 130, amber: 75, rose: 15, slate: 260 };
+/** The swatch colours: the same lightness for all, and slate nearly grey (a low chroma) so it doesn't read as another blue. */
+export const PROJECT_SWATCH: Record<ProjectColor, string> = Object.fromEntries(
+ Object.entries(PROJECT_HUE).map(([c, h]) => [c, `oklch(0.68 ${c === "slate" ? 0.025 : 0.13} ${h})`]),
+) as Record<ProjectColor, string>;
export type SourceKind = "link" | "file" | "image" | "video" | "audio" | "element" | "text";
diff --git a/src/server/assist/agent.ts b/src/server/assist/agent.ts
index a204f3e5..66932be4 100644
--- a/src/server/assist/agent.ts
+++ b/src/server/assist/agent.ts
@@ -262,6 +262,27 @@ export function getThread(id: string): AssistThreadView | null {
return { thread: s.thread, generations };
}
+/** What a project's chats made (its Assets tab): their finished generations, newest first, with the chat each came from. */
+export function projectAssets(projectId: string, limit = 120): { generation: Generation; chatId: string; chatTitle: string }[] {
+ const rows = db()
+ .prepare("SELECT t.id, t.title, t.items_json FROM assist_threads t JOIN assist_thread_state s ON s.thread_id = t.id WHERE s.project_id = ? ORDER BY t.updated_at DESC")
+ .all(projectId) as { id: string; title: string; items_json: string }[];
+ const seen = new Set<string>();
+ const out: { generation: Generation; chatId: string; chatTitle: string }[] = [];
+ for (const r of rows) {
+ for (const item of JSON.parse(r.items_json) as AssistItem[]) {
+ if (item.role !== "generations") continue;
+ for (const gid of item.ids) {
+ if (seen.has(gid)) continue;
+ seen.add(gid);
+ const g = getGeneration(gid);
+ if (g?.status === "succeeded" && g.outputs.length) out.push({ generation: g, chatId: r.id, chatTitle: r.title });
+ }
+ }
+ }
+ return out.sort((a, b) => b.generation.createdAt - a.generation.createdAt).slice(0, limit);
+}
+
export function deleteThread(id: string): void {
db().transaction(() => {
db().prepare("DELETE FROM assist_threads WHERE id = ?").run(id);
diff --git a/tests/assist-context.test.ts b/tests/assist-context.test.ts
index 345b264e..6a662237 100644
--- a/tests/assist-context.test.ts
+++ b/tests/assist-context.test.ts
@@ -394,6 +394,29 @@ describe("studio tools", () => {
});
});
+describe("a project's assets", () => {
+ it("are the finished results of its chats, newest first, with the chat each came from", async () => {
+ const p = projects.createProject({ name: "Assets project" });
+ const t = agent.createThread({ engine: "cloud", agent: "offline", projectId: p.id, autoApprove: true });
+ agent.addMessage(t.id, "Two stills of a red kite");
+ const gen = { summary: "Kites", jobs: [{ model_id: "nano-banana-pro", prompt: "a red kite", outputs: 2 }] };
+ await agent.run(t.id, scripted(reply([use("u1", "generate", gen)], "tool_use"), reply([text("Started.")], "end_turn")).call);
+ const ids = agent.getThread(t.id)!.thread.items.flatMap((i) => (i.role === "generations" ? i.ids : []));
+ expect(ids.length).toBeGreaterThan(0);
+ // Not finished yet: nothing to show.
+ db().prepare("UPDATE generations SET status = 'running' WHERE id IN (" + ids.map(() => "?").join(",") + ")").run(...ids);
+ expect(agent.projectAssets(p.id)).toEqual([]);
+ db()
+ .prepare("UPDATE generations SET status = 'succeeded', outputs_json = ? WHERE id = ?")
+ .run(JSON.stringify([{ url: "/samples/previews/city.svg", contentType: "image/svg+xml" }]), ids[0]);
+ const assets = agent.projectAssets(p.id);
+ expect(assets).toHaveLength(1);
+ expect(assets[0]).toMatchObject({ chatId: t.id, chatTitle: "Two stills of a red kite", generation: { id: ids[0], status: "succeeded" } });
+ // A chat outside the project doesn't count.
+ expect(agent.projectAssets("nope")).toEqual([]);
+ });
+});
+
describe("MCP", () => {
const rpc = (method: string, params?: unknown) => handleMcp({ jsonrpc: "2.0", id: 7, method, params });