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.

Polish: Cinema uses the shared live stream, not-found states for unknown ids, real 404 for unknown apps, 390 px sweep covers dynamic routes; Assist tests

Claude603d41936bc4
diff --git a/src/components/canvas/canvas-editor.tsx b/src/components/canvas/canvas-editor.tsx
index 6dba60c5..ddbeb1b7 100644
--- a/src/components/canvas/canvas-editor.tsx
+++ b/src/components/canvas/canvas-editor.tsx
@@ -29,9 +29,9 @@ import Link from "next/link";
import { useTheme } from "next-themes";
import { memo, useCallback, useDeferredValue, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { toast } from "sonner";
+import { ErrorState, NotFoundState } from "@/components/empty-state";
import { Button } from "@/components/ui/button";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
-import { Empty, EmptyContent, EmptyDescription, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { Kbd } from "@/components/ui/kbd";
import { SidebarTrigger } from "@/components/ui/sidebar";
import { Skeleton } from "@/components/ui/skeleton";
@@ -133,24 +133,9 @@ export function CanvasEditor({ id }: { id: string }) {
const view = useCanvasView(id);
if (view.isLoading) return <EditorSkeleton />;
if (!view.data) {
- return (
- <div className="flex min-h-svh flex-col">
- <div className="flex h-14 items-center px-3 md:hidden">
- <SidebarTrigger />
- </div>
- <Empty className="flex-1">
- <EmptyHeader>
- <EmptyTitle className="text-[22px]">This canvas isn&apos;t here</EmptyTitle>
- <EmptyDescription>It may have been deleted. Your results are still in the library.</EmptyDescription>
- </EmptyHeader>
- <EmptyContent>
- <Button asChild variant="secondary">
- <Link href="/canvas">All canvases</Link>
- </Button>
- </EmptyContent>
- </Empty>
- </div>
- );
+ // A canvas that isn't there gets the shared 404 state; a request that failed otherwise can be retried.
+ if (view.error && (view.error as { status?: number }).status !== 404) return <ErrorState error={view.error} retry={() => void view.refetch()} />;
+ return <NotFoundState title="This canvas isn’t here">It may have been deleted. Its results are still in your library.</NotFoundState>;
}
return (
<ReactFlowProvider>
diff --git a/src/components/cinema/hooks.ts b/src/components/cinema/hooks.ts
index 6c1932ec..eccaced7 100644
--- a/src/components/cinema/hooks.ts
+++ b/src/components/cinema/hooks.ts
@@ -1,10 +1,10 @@
"use client";
-import { useMutation, useQuery, useQueryClient, type QueryClient } from "@tanstack/react-query";
-import { useEffect, useState, useSyncExternalStore } from "react";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { useEffect, useState } from "react";
import type { CinemaFolder, CinemaGenerateInput, CinemaProject, CinemaTile, DirectorMessage, DirectorSettings } from "@/lib/catalog/cinema";
import type { Generation } from "@/lib/catalog/types";
-import { toStreamEvent } from "@/lib/generation-stream";
+import { useGenerationEvents } from "@/lib/api";
import { Autosaver } from "./autosave";
import { applyToTakes, type CinemaGeneration } from "./live";
@@ -33,57 +33,20 @@ const send = async <T,>(url: string, method: string, body?: unknown, keepalive =
const active = (g: Generation) => g.status === "queued" || g.status === "running";
// ---------------------------------------------------------------------------
-// Live updates: one EventSource on GET /api/generations/stream for the workspace's lists. While it's
-// connected the takes update in place and polling drops to a slow safety net.
+// Live updates: the app's one shared generation stream (useGenerationEvents in lib/api.ts, one
+// connection per browser rather than one per Cinema tab). While it's connected the takes update in
+// place and polling drops to a slow safety net.
-const live = { es: null as EventSource | null, users: 0, connected: false, client: null as QueryClient | null, listeners: new Set<() => void>() };
-
-function setConnected(v: boolean) {
- if (live.connected === v) return;
- live.connected = v;
- live.listeners.forEach((l) => l());
-}
-
-function applyEvent(qc: QueryClient, data: string, event: string) {
- const ev = toStreamEvent({ event, data });
- if (!ev) return;
- for (const q of qc.getQueryCache().findAll({ queryKey: ["cinema"] })) {
- const k = q.queryKey;
- if (!(k[2] === "items" || k[1] === "studio")) continue;
- const old = q.state.data as CinemaGeneration[] | undefined;
+/** Patch one cached list of takes with a live event (cinema keeps its own caches). */
+function useLiveTakes(queryKey: readonly unknown[]): boolean {
+ const qc = useQueryClient();
+ const key = JSON.stringify(queryKey);
+ return useGenerationEvents((ev) => {
+ const k = JSON.parse(key) as unknown[];
+ const old = qc.getQueryData<CinemaGeneration[]>(k);
const next = applyToTakes(old, ev);
if (next !== old) qc.setQueryData(k, next);
- }
-}
-
-function useCinemaStream(): boolean {
- const qc = useQueryClient();
- useEffect(() => {
- live.client = qc;
- live.users++;
- if (!live.es && typeof EventSource !== "undefined") {
- const es = new EventSource("/api/generations/stream");
- es.onopen = () => setConnected(true);
- es.onerror = () => setConnected(false);
- for (const event of ["generation", "deleted"]) es.addEventListener(event, (m) => live.client && applyEvent(live.client, (m as MessageEvent<string>).data, event));
- live.es = es;
- }
- return () => {
- live.users--;
- if (live.users) return;
- live.es?.close();
- live.es = null;
- setConnected(false);
- };
- }, [qc]);
- return useSyncExternalStore(
- (cb) => {
- live.listeners.add(cb);
- return () => live.listeners.delete(cb);
- },
- () => live.connected,
- () => false,
- );
+ });
}
const pollEvery = (items: Generation[] | undefined, connected: boolean) => (items?.some(active) ? (connected ? 10_000 : 1500) : false);
@@ -108,7 +71,7 @@ export function useCinemaProject(id: string) {
/** Every take in the project (folders are filtered in the browser); live, with polling as a fallback. */
export function useCinemaItems(id: string) {
- const connected = useCinemaStream();
+ const connected = useLiveTakes(["cinema", id, "items"]);
return useQuery({
queryKey: ["cinema", id, "items"],
queryFn: async () => (await json<{ items: CinemaGeneration[] }>(await fetch(`/api/cinema/projects/${id}/items`))).items,
@@ -118,7 +81,7 @@ export function useCinemaItems(id: string) {
/** "My Generations": every Cinema Studio generation, in any project (each with its projectId). */
export function useStudioGenerations(id: string, enabled: boolean) {
- const connected = useCinemaStream();
+ const connected = useLiveTakes(["cinema", "studio"]);
return useQuery({
queryKey: ["cinema", "studio"],
enabled,
diff --git a/src/components/cinema/workspace.tsx b/src/components/cinema/workspace.tsx
index b6c28a23..3f278285 100644
--- a/src/components/cinema/workspace.tsx
+++ b/src/components/cinema/workspace.tsx
@@ -6,6 +6,7 @@ import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
import { toast } from "sonner";
+import { ErrorState, NotFoundState } from "@/components/empty-state";
import { Button } from "@/components/ui/button";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet";
@@ -135,21 +136,11 @@ export function CinemaWorkspace({ id }: { id: string }) {
</div>
</div>
);
- if (!project.data)
- return (
- <div className="flex h-svh flex-col">
- <div className="flex h-14 items-center px-3 md:hidden">
- <SidebarTrigger />
- </div>
- <div className="mx-auto max-w-sm pt-[18vh] text-center">
- <p className="font-heading text-[26px]">This project doesn&apos;t exist</p>
- <p className="mt-1 text-[14px] text-muted-foreground">It may have been deleted.</p>
- <Button asChild className="mt-5">
- <Link href="/cinema">All projects</Link>
- </Button>
- </div>
- </div>
- );
+ if (!project.data) {
+ // A project that isn't there gets the shared 404 state; a request that failed otherwise can be retried.
+ if (project.error && !/not found/i.test(project.error.message)) return <ErrorState error={project.error} retry={() => void project.refetch()} />;
+ return <NotFoundState title="This project doesn’t exist">It may have been deleted. Its takes are still in your library.</NotFoundState>;
+ }
return <Workspace data={project.data} items={items.data ?? []} loading={items.isLoading} />;
}
diff --git a/src/components/empty-state.tsx b/src/components/empty-state.tsx
index 7f2a05f4..b2e0fdf4 100644
--- a/src/components/empty-state.tsx
+++ b/src/components/empty-state.tsx
@@ -45,6 +45,7 @@ const SECTIONS: { prefix: string; href: string; label: string }[] = [
{ prefix: "/library", href: "/library", label: "Your library" },
{ prefix: "/cinema", href: "/cinema", label: "Cinema projects" },
{ prefix: "/canvas", href: "/canvas", label: "Your canvases" },
+ { prefix: "/assist", href: "/assist", label: "Back to Assist" },
];
function SectionLink() {
diff --git a/src/lib/assist.ts b/src/lib/assist.ts
index 5c04fe02..f5e10109 100644
--- a/src/lib/assist.ts
+++ b/src/lib/assist.ts
@@ -443,7 +443,7 @@ export function parseMemoryImport(text: string): { category: MemoryCategory; tex
const l = line.trim();
if (!l) continue;
const h = /^(?:#{1,6}\s+|\*\*)?([A-Za-z ]{3,24}?)(?:\*\*)?\s*:?\s*$/.exec(l);
- if (h && toCategory(h[1]) && !/^[-*•]/.test(l)) {
+ if (h && toCategory(h[1]) && !/^[-*•]\s/.test(l)) {
heading = toCategory(h[1]);
continue;
}
diff --git a/src/proxy.ts b/src/proxy.ts
index 409cf48e..06159936 100644
--- a/src/proxy.ts
+++ b/src/proxy.ts
@@ -1,9 +1,31 @@
import { NextResponse, type NextRequest } from "next/server";
+import { APPS } from "@/lib/catalog/apps";
import { authEnabled, crossSite, hostAllowed, SESSION_COOKIE, validSession, validToken } from "@/server/auth";
/** Paths that work signed out: the login page and its API. */
const OPEN = new Set(["/login", "/api/auth/login"]);
+const APP_IDS = new Set(APPS.map((a) => a.id));
+
+/**
+ * Let the request through — except /apps/<id> for an app that doesn't exist, which gets a real 404.
+ * The page can't send one itself: the studio's loading.tsx streams the shell (with a 200) before
+ * the page knows the id is unknown.
+ */
+function pass(request: NextRequest): NextResponse {
+ const app = /^\/apps\/([^/]+)\/?$/.exec(request.nextUrl.pathname)?.[1];
+ if (app && !APP_IDS.has(safeDecode(app))) return NextResponse.rewrite(new URL("/_fuobe-not-found", request.url), { status: 404 });
+ return NextResponse.next();
+}
+
+function safeDecode(s: string): string {
+ try {
+ return decodeURIComponent(s);
+ } catch {
+ return s;
+ }
+}
+
export function proxy(request: NextRequest) {
// DNS rebinding: a page whose own name now points at this machine. Every method, reads too. With a
// password set the sign-in check below already stops it (the session cookie belongs to the real name).
@@ -18,10 +40,10 @@ export function proxy(request: NextRequest) {
if (crossSite(request, request.nextUrl.host)) {
return NextResponse.json({ error: "Blocked a request from another website. Use Fuobe from its own address (or add it to FUOBE_ALLOWED_ORIGINS)." }, { status: 403 });
}
- if (!authEnabled()) return NextResponse.next();
+ if (!authEnabled()) return pass(request);
const { pathname, search } = request.nextUrl;
if (OPEN.has(pathname)) return NextResponse.next();
- if (validSession(request.cookies.get(SESSION_COOKIE)?.value) || validToken(request.headers.get("authorization"))) return NextResponse.next();
+ if (validSession(request.cookies.get(SESSION_COOKIE)?.value) || validToken(request.headers.get("authorization"))) return pass(request);
if (pathname.startsWith("/api/")) {
return NextResponse.json({ error: "Sign in, or send an API token as Authorization: Bearer fuobe_…" }, { status: 401, headers: { "WWW-Authenticate": 'Bearer realm="fuobe"' } });
}
diff --git a/tests/assist-context.test.ts b/tests/assist-context.test.ts
new file mode 100644
index 00000000..e43319a1
--- /dev/null
+++ b/tests/assist-context.test.ts
@@ -0,0 +1,334 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+import type Anthropic from "@anthropic-ai/sdk";
+
+vi.setConfig({ testTimeout: 60_000 });
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-assist-ctx-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+process.env.OLLAMA_URL = "http://127.0.0.1:9";
+
+const { setSetting } = await import("@/server/settings");
+const agent = await import("@/server/assist/agent");
+const tools = await import("@/server/assist/tools");
+const studio = await import("@/server/assist/studio-tools");
+const memory = await import("@/server/assist/memory");
+const projects = await import("@/server/assist/projects");
+const { handleMcp } = await import("@/server/mcp");
+const { db } = await import("@/server/db");
+
+type Msg = Anthropic.Beta.BetaMessage;
+type Block = Anthropic.Beta.BetaContentBlock;
+type Param = Anthropic.Beta.BetaMessageParam;
+const text = (t: string) => ({ type: "text", text: t, citations: null }) as Block;
+const use = (id: string, name: string, input: unknown) => ({ type: "tool_use", id, name, input }) as unknown as Block;
+const reply = (content: Block[], stop: Anthropic.Beta.BetaStopReason, extra: Partial<Msg> = {}) => ({ content, stop_reason: stop, stop_details: null, ...extra }) as Msg;
+
+/** A model that answers from a script and records each request. */
+function scripted(...turns: Msg[]) {
+ const seen: { system: { stable: string; turn: string }; messages: Param[] }[] = [];
+ const call: import("@/server/assist/agent").ModelCall = async ({ system, messages }) => {
+ seen.push({ system: structuredClone(system), messages: structuredClone(messages) });
+ const next = turns.shift();
+ if (!next) throw new Error("script ran out");
+ return next;
+ };
+ return { call, seen };
+}
+const history = (id: string) => JSON.parse((db().prepare("SELECT messages_json FROM assist_threads WHERE id = ?").get(id) as { messages_json: string }).messages_json) as Param[];
+const sysText = (m: Param) => (typeof m.content === "string" ? m.content : m.content.map((b) => ("text" in b ? b.text : "")).join(""));
+
+beforeAll(() => setSetting("demoMode", "auto"));
+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
+
+describe("a chat's context", () => {
+ it("freezes the system prompt at the first call and appends changes as one Context update", async () => {
+ memory.addMemory({ text: "Prefers vertical 9:16", category: "Preference" });
+ const t = agent.createThread({ engine: "cloud", agent: "offline" });
+ agent.addMessage(t.id, "Hello");
+ const m = scripted(reply([text("Hi!")], "end_turn"), reply([text("Noted.")], "end_turn"), reply([text("Again.")], "end_turn"));
+ await agent.run(t.id, m.call);
+ const first = m.seen[0].system.turn;
+ expect(first).toContain("[Preference] Prefers vertical 9:16");
+ expect(first).toContain("/product-photoshoot — Product Photographer");
+ expect(first).toMatch(/Ask-first is on/);
+ expect(m.seen[0].system.stable).toMatch(/load_skill/);
+ // Something changes: a new memory and auto-run.
+ memory.addMemory({ text: "Brand colour is teal", category: "Convention" });
+ await agent.updateThread(t.id, { autoApprove: true });
+ agent.addMessage(t.id, "Next");
+ await agent.run(t.id, m.call);
+ expect(m.seen[1].system).toEqual(m.seen[0].system);
+ const last = m.seen[1].messages.at(-1)!;
+ expect(last.role).toBe("system");
+ expect(sysText(last)).toMatch(/^Context update/);
+ expect(sysText(last)).toContain("Brand colour is teal");
+ expect(sysText(last)).toContain("Auto-run is on");
+ expect(sysText(last)).not.toContain("Prefers vertical 9:16");
+ // It stays in the history (append-only), right before the reply it led to; nothing new next time.
+ const h = history(t.id);
+ expect(h.map((x) => x.role)).toEqual(["user", "assistant", "user", "system", "assistant"]);
+ agent.addMessage(t.id, "Once more");
+ await agent.run(t.id, m.call);
+ expect(m.seen[2].messages.at(-1)!.role).toBe("user");
+ expect(m.seen[2].messages.slice(0, 5)).toEqual(h);
+ });
+
+ it("doesn't commit an update the model refused to answer", async () => {
+ const t = agent.createThread({ engine: "cloud", agent: "offline" });
+ agent.addMessage(t.id, "Hi");
+ await agent.run(t.id, scripted(reply([text("Hello")], "end_turn")).call);
+ memory.addMemory({ text: "Likes film grain", category: "Style" });
+ agent.addMessage(t.id, "Something");
+ const m = scripted(reply([], "refusal", { stop_details: { type: "refusal", category: null, explanation: "No." } as never }), reply([text("ok")], "end_turn"));
+ await agent.run(t.id, m.call);
+ expect(history(t.id).some((x) => x.role === "system")).toBe(false);
+ agent.addMessage(t.id, "Try again");
+ await agent.run(t.id, m.call);
+ expect(sysText(m.seen[1].messages.at(-1)!)).toContain("Likes film grain");
+ });
+
+ it("loads a skill named with /name before the first call, and shows it on the message", async () => {
+ const t = agent.createThread({ engine: "cloud", agent: "offline" });
+ const th = agent.addMessage(t.id, "/product-photoshoot a matte black perfume bottle");
+ expect(th.skills).toEqual(["product-photoshoot"]);
+ expect(th.items.at(-1)).toMatchObject({ role: "user", text: "a matte black perfume bottle", skills: ["product-photoshoot"] });
+ expect(th.title).toBe("a matte black perfume bottle");
+ const m = scripted(reply([text("Shooting it.")], "end_turn"));
+ await agent.run(t.id, m.call);
+ expect(m.seen[0].system.turn).toContain("### /product-photoshoot — Product Photographer");
+ expect(sysText(m.seen[0].messages[0])).toBe("a matte black perfume bottle");
+ // Only "/katana" plus files: the model still gets words to act on.
+ const k = agent.createThread({ engine: "cloud", agent: "offline" });
+ agent.addMessage(k.id, "/katana", ["/api/files/uploads/x.mp4"]);
+ expect(sysText(history(k.id)[0])).toMatch(/^Use the Katana skill with the attached files\./);
+ });
+
+ it("load_skill adds the skill's instructions as a system message right after its result", async () => {
+ const t = agent.createThread({ engine: "cloud", agent: "offline" });
+ agent.addMessage(t.id, "Make me a thumbnail");
+ const m = scripted(reply([use("toolu_ls", "load_skill", { name: "thumbnail-generation" })], "tool_use"), reply([text("Following it.")], "end_turn"));
+ await agent.run(t.id, m.call);
+ const second = m.seen[1].messages;
+ expect(second.at(-2)!.role).toBe("user");
+ expect(JSON.stringify(second.at(-2)!.content)).toMatch(/Loaded \/thumbnail-generation/);
+ expect(second.at(-1)!.role).toBe("system");
+ expect(sysText(second.at(-1)!)).toContain("### /thumbnail-generation — Thumbnail Generator");
+ const v = agent.getThread(t.id)!;
+ expect(v.thread.skills).toEqual(["thumbnail-generation"]);
+ expect(v.thread.items.find((i) => i.role === "tool")).toMatchObject({ text: "Using the Thumbnail Generator skill", href: "/assist/skills?skill=thumbnail-generation" });
+ });
+
+ it("asks before remembering in ask-first mode, then saves the memory where the chat lives", async () => {
+ const p = projects.createProject({ name: "Remember project" });
+ const t = agent.createThread({ engine: "cloud", agent: "offline", projectId: p.id });
+ agent.addMessage(t.id, "Our logo is always bottom right");
+ const m = scripted(reply([use("toolu_r", "remember", { text: "Logo always bottom right.", category: "Convention" })], "tool_use"), reply([text("Got it.")], "end_turn"));
+ await agent.run(t.id, m.call);
+ let v = agent.getThread(t.id)!;
+ expect(v.thread.status).toBe("waiting");
+ expect(v.thread.items.find((i) => i.role === "approval")).toMatchObject({ summary: "Remember this?", jobs: [{ tool: "remember", op: "memory", prompt: "Logo always bottom right.", note: "This project" }] });
+ expect(memory.listMemories({ scope: "project", projectId: p.id })).toHaveLength(0);
+ await agent.answerApproval(t.id, true);
+ await agent.run(t.id, m.call);
+ v = agent.getThread(t.id)!;
+ expect(memory.listMemories({ scope: "project", projectId: p.id }).map((x) => [x.text, x.source])).toEqual([["Logo always bottom right.", "agent"]]);
+ expect(v.thread.items.some((i) => i.role === "tool" && /Remembered/.test(i.text))).toBe(true);
+ });
+
+ it("gives project chats the instructions and sources, and read_source the full text", async () => {
+ const p = projects.createProject({ name: "Launch", instructions: "Always pastel. Always 9:16.", skills: ["product-photoshoot", "thumbnail-generation"] });
+ const note = await projects.addSource(p.id, { kind: "text", title: "Brief", text: `${"Context. ".repeat(60)}The drop is on Friday.` });
+ const t = agent.createThread({ engine: "cloud", agent: "offline", projectId: p.id });
+ agent.addMessage(t.id, "Plan the shoot");
+ const m = scripted(reply([use("toolu_s", "read_source", { id: note.id })], "tool_use"), reply([text("Planned.")], "end_turn"));
+ await agent.run(t.id, m.call);
+ const ctx = m.seen[0].system.turn;
+ expect(ctx).toContain("This chat is in the project “Launch”");
+ expect(ctx).toContain("Always pastel. Always 9:16.");
+ expect(ctx).toContain(`[${note.id}] text: Brief`);
+ // Project skills only.
+ expect(ctx).toContain("/thumbnail-generation");
+ expect(ctx).not.toContain("/katana —");
+ expect(JSON.stringify(m.seen[1].messages.at(-1)!.content)).toContain("The drop is on Friday.");
+ // /name of a skill the project doesn't offer stays plain text.
+ agent.addMessage(t.id, "/katana do it");
+ expect(agent.getThread(t.id)!.thread.skills).toEqual([]);
+ });
+});
+
+describe("modes", () => {
+ it("falls back from Smart and Manual Claude to Free without a key, with a note", async () => {
+ setSetting("anthropicKey", "");
+ expect(await agent.resolveMode({ mode: "smart" })).toMatchObject({ mode: "free", agent: "offline", note: expect.stringMatching(/Anthropic API key/) });
+ expect(await agent.resolveMode({ mode: "manual", agent: "claude", model: "claude-haiku-5-5" })).toMatchObject({ agent: "offline", note: expect.any(String) });
+ expect(await agent.resolveMode({ mode: "manual", agent: "offline" })).toMatchObject({ mode: "manual", agent: "offline" });
+ expect(await agent.resolveMode({ mode: "manual", agent: "ollama", model: "llama3.2:3b" })).toMatchObject({ agent: "ollama", model: "llama3.2:3b", note: expect.stringMatching(/Ollama isn't answering/) });
+ expect(await agent.resolveMode({ mode: "manual", agent: "ollama", model: "bad name; rm -rf" })).toMatchObject({ model: null });
+ setSetting("enhanceProvider", "none");
+ expect(await agent.resolveMode({ mode: "smart" })).toMatchObject({ agent: "offline", note: expect.stringMatching(/AI helper is off/) });
+ setSetting("enhanceProvider", "auto");
+ expect((await agent.availability()).defaultMode).toBe("free");
+ });
+
+ it("sends the picked Claude model and effort; only models with fallbacks get them", async () => {
+ setSetting("anthropicKey", "sk-ant-test");
+ try {
+ expect(await agent.resolveMode({ mode: "smart" })).toMatchObject({ agent: "claude", model: "claude-opus-5-5", effort: "medium" });
+ const r = await agent.resolveMode({ mode: "manual", agent: "claude", model: "claude-haiku-5-5", effort: "high" });
+ const t = agent.createThread({ engine: "cloud", agent: r.agent, mode: r.mode, model: r.model, effort: r.effort });
+ agent.addMessage(t.id, "Hi");
+ const sent: { headers: Headers; body: Record<string, unknown> }[] = [];
+ const realFetch = globalThis.fetch;
+ globalThis.fetch = (async (_url: string, init: RequestInit) => {
+ sent.push({ headers: new Headers(init.headers), body: JSON.parse(String(init.body)) });
+ return new Response(JSON.stringify({ id: "msg_1", type: "message", role: "assistant", model: "claude-haiku-5-5", stop_sequence: null, stop_details: null, usage: { input_tokens: 1, output_tokens: 1 }, content: [{ type: "text", text: "Hello" }], stop_reason: "end_turn" }), {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ });
+ }) as typeof fetch;
+ try {
+ await agent.run(t.id);
+ // Switch to Opus mid-chat: the same frozen system prompt goes to the new model.
+ await agent.updateThread(t.id, { mode: { mode: "manual", agent: "claude", model: "claude-opus-5-5", effort: "max" } });
+ agent.addMessage(t.id, "Again");
+ await agent.run(t.id);
+ } finally {
+ globalThis.fetch = realFetch;
+ }
+ const [a, b] = sent;
+ expect(a.body).toMatchObject({ model: "claude-haiku-5-5", output_config: { effort: "high" }, thinking: { type: "adaptive", block_binding: { prefix_mismatch_behavior: "drop_block" } }, cache_control: { type: "ephemeral" } });
+ expect(a.body.fallbacks).toBeUndefined();
+ expect(a.headers.get("anthropic-beta")).toBe("thinking-binding-controls-2026-08-01");
+ expect(b.body).toMatchObject({ model: "claude-opus-5-5", output_config: { effort: "max" }, fallbacks: "default" });
+ expect(b.headers.get("anthropic-beta")).toContain("server-side-fallback-2026-07-01");
+ expect(b.body.system).toEqual(a.body.system);
+ const v = agent.getThread(t.id)!.thread;
+ expect(v).toMatchObject({ mode: "manual", agent: "claude", model: "claude-opus-5-5", effort: "max" });
+ } finally {
+ setSetting("anthropicKey", "");
+ }
+ });
+
+ it("the offline planner follows a loaded skill's hints and turns 'remember that' into a memory", () => {
+ expect(agent.offlinePlan("a cozy cafe", "cloud", { kind: "video", aspect: "9:16", style: "handheld" })).toMatchObject({
+ input: { jobs: [{ model_id: "seedance-2-5", aspect_ratio: "9:16", prompt: "a cozy cafe. handheld" }] },
+ });
+ expect(agent.offlinePlan("a cozy cafe", "cloud", { kind: "image", outputs: 4, aspect: "1:1" })).toMatchObject({ input: { jobs: [{ outputs: 4, aspect_ratio: "1:1" }] } });
+ expect(agent.offlinePlan("Remember that I always want vertical 9:16 videos", "cloud")).toEqual({ tool: "remember", input: { text: "I always want vertical 9:16 videos.", category: "Convention" }, say: "I'll remember that for every chat." });
+ });
+});
+
+describe("studio tools", () => {
+ const plan = (name: string, input: unknown, engine: "cloud" | "open" = "open") => tools.planFor(name, input, { engine });
+ const video = "/api/files/uploads/2026-10-19/clip.mp4";
+
+ it("are in the tool list with closed schemas, gated, and not strict", () => {
+ const api = tools.apiTools();
+ for (const n of ["split_layers", "restyle_footage", "dub_video", "faceless_episode", "create_ads", "add_captions", "list_skills", "load_skill", "remember", "read_source"]) {
+ const t = api.find((x) => x.name === n);
+ expect(t, n).toBeTruthy();
+ expect(t!.strict).toBeUndefined();
+ }
+ expect(new Set(api.map((t) => t.name)).size).toBe(api.length);
+ expect(tools.getTool("dub_video")!.gated).toBe(true);
+ });
+
+ it("dub on the open engine: stems → transcript → translation → cloned voice → lip sync → mix, per language", () => {
+ const steps = studio.fallbackSteps.dub({ video, languages: ["Spanish", "German"] }, { engine: "open" });
+ expect(steps.map((s) => s.request.op)).toEqual(["separate-audio", "transcribe", "translate", "tts", "lipsync", "mux", "translate", "tts", "lipsync", "mux"]);
+ expect(steps.find((s) => s.key === "voice1")).toMatchObject({ after: ["tr1", "stems"], chain: [{ slot: "prompt" }, { slot: "voiceAudio", stem: "voice" }] });
+ expect(steps.find((s) => s.key === "film0")).toMatchObject({ after: ["lips0", "voice0", "stems"], chain: [{ slot: "video" }, { slot: "audio" }, { slot: "audio2", stem: "background" }] });
+ expect(steps[3].request.step).toMatchObject({ label: "Voice · Spanish", of: 10 });
+ const noLips = studio.fallbackSteps.dub({ video, languages: ["French"], lipsync: false }, { engine: "open" });
+ expect(noLips.map((s) => s.request.op)).toEqual(["separate-audio", "transcribe", "translate", "tts", "mux"]);
+ // Cloud: one HeyGen job per language.
+ expect(studio.fallbackSteps.dub({ video, languages: ["Spanish"] }, { engine: "cloud" }).map((s) => [s.request.modelId, s.request.params?.targetLanguage])).toEqual([["heygen-translate", "Spanish"]]);
+ const jobs = plan("dub_video", { video, languages: ["Spanish"] });
+ expect(jobs.jobs).toHaveLength(6);
+ expect(jobs.jobs.every((j) => !j.error)).toBe(true);
+ });
+
+ it("a faceless episode joins its clips in groups of four on the open engine", () => {
+ const scenes = Array.from({ length: 6 }, (_, i) => ({ narration: `Line ${i}`, visual: `Scene ${i}` }));
+ const steps = studio.fallbackSteps.faceless({ scenes, style: "flat 2D", aspect_ratio: "9:16" }, { engine: "open" });
+ expect(steps.filter((s) => s.request.op === "t2i")).toHaveLength(6);
+ expect(steps.filter((s) => s.request.op === "concat").map((s) => s.key)).toEqual(["part0", "part1", "film"]);
+ expect(steps.find((s) => s.key === "episode")).toMatchObject({ after: ["film", "voice"], request: { op: "mux", modelId: "oss-mux" } });
+ expect(steps.find((s) => s.key === "voice")!.request.prompt).toBe(scenes.map((s) => s.narration).join("\n\n"));
+ const cloud = studio.fallbackSteps.faceless({ scenes, style: "flat 2D" }, { engine: "cloud" });
+ expect(cloud.filter((s) => s.request.op === "concat")).toHaveLength(1);
+ expect(cloud.find((s) => s.key === "clip0")!.request.modelId).toBe("gemini-omni-flash");
+ expect(() => studio.fallbackSteps.faceless({ scenes: scenes.slice(0, 1), style: "x" }, { engine: "open" })).toThrow(/at least 2 scenes/);
+ });
+
+ it("captions, layers, restyle and ads plan with real models", () => {
+ expect(studio.fallbackSteps.captions({ video, translate_to: "Spanish" }, { engine: "open" }).map((s) => s.request.modelId)).toEqual(["oss-qwen3-asr", "oss-text-llm", "oss-captions-burnin"]);
+ expect(studio.fallbackSteps.captions({ video, translate_to: "Spanish" }, { engine: "cloud" })[0].request).toMatchObject({ modelId: "veed-subtitles", params: { targetLanguage: "Spanish" } });
+ expect(plan("split_layers", { image: "/api/files/uploads/a.png", layers: 5 }).jobs).toMatchObject([{ op: "layers", modelId: "oss-qwen-layered" }]);
+ expect(plan("restyle_footage", { video, style: "claymation" }, "cloud").jobs).toMatchObject([{ op: "v2v", modelId: "kling-o3" }]);
+ const ads = studio.fallbackSteps.ads({ brief: "oat milk", product_image: "/api/files/uploads/p.png", count: 8, aspect_ratios: ["1:1", "4:5", "9:16"] }, { engine: "cloud" });
+ expect(ads).toHaveLength(12);
+ expect(ads[0]).toMatchObject({ modelId: "nano-banana-pro", op: "edit", inputs: { images: ["/api/files/uploads/p.png"] } });
+ });
+
+ it("runs as one demo pipeline, final result in the chat", async () => {
+ const out = await tools.executeTool("dub_video", { video, languages: ["Spanish"], lipsync: false }, { engine: "open" });
+ expect(out.isError).toBeFalsy();
+ const body = JSON.parse(out.content as string) as { steps: { id: string; waitsFor: string[] }[]; results: string[]; demo: boolean };
+ expect(body.steps).toHaveLength(5);
+ expect(body.demo).toBe(true);
+ expect(body.results).toHaveLength(1);
+ expect(out.items?.find((i) => i.role === "generations")).toMatchObject({ ids: body.results });
+ const deps = db().prepare("SELECT depends_on FROM generations WHERE id = ?").get(body.results[0]) as { depends_on: string };
+ expect(JSON.parse(deps.depends_on)).toEqual(body.steps.at(-1)!.waitsFor);
+ });
+
+ it("hands the job to a studio module once one is wired in", async () => {
+ const seen: unknown[] = [];
+ studio.STUDIO_ROUTES.split_layers = { run: async (i) => (seen.push(i), { ids: [], href: "/layers/abc", info: { project: "abc" } }) };
+ try {
+ const out = await tools.executeTool("split_layers", { image: "/api/files/uploads/a.png" }, { engine: "open" });
+ expect(seen).toEqual([{ image: "/api/files/uploads/a.png" }]);
+ expect(JSON.parse(out.content as string)).toEqual({ results: [], open: "/layers/abc", project: "abc" });
+ expect(out.items).toEqual([{ id: "", role: "tool", text: "Opened a Layers project", href: "/layers/abc" }]);
+ } finally {
+ delete studio.STUDIO_ROUTES.split_layers;
+ }
+ });
+});
+
+describe("MCP", () => {
+ const rpc = (method: string, params?: unknown) => handleMcp({ jsonrpc: "2.0", id: 7, method, params });
+
+ it("offers skills as prompts", async () => {
+ const init = (await rpc("initialize", { protocolVersion: "2025-11-25" })) as { result: { capabilities: { prompts?: unknown } } };
+ expect(init.result.capabilities.prompts).toBeTruthy();
+ const list = (await rpc("prompts/list")) as { result: { prompts: { name: string; arguments: unknown[] }[] } };
+ expect(list.result.prompts.map((p) => p.name)).toContain("product-photoshoot");
+ const got = (await rpc("prompts/get", { name: "faceless-video", arguments: { request: "a 60s history of tea" } })) as { result: { messages: { content: { text: string } }[] } };
+ expect(got.result.messages[0].content.text).toMatch(/Faceless Studio[\s\S]*The job: a 60s history of tea$/);
+ expect(await rpc("prompts/get", { name: "nope" })).toMatchObject({ error: { code: -32602 } });
+ });
+
+ it("lists the new tools with the right hints and prices studio jobs", async () => {
+ const r = (await rpc("tools/list")) as { result: { tools: { name: string; description: string; annotations: { readOnlyHint: boolean; openWorldHint: boolean } }[] } };
+ const by = Object.fromEntries(r.result.tools.map((t) => [t.name, t]));
+ expect(by.load_skill.annotations.readOnlyHint).toBe(true);
+ expect(by.dub_video.description).toMatch(/estimate_job/);
+ expect(by.dub_video.description).not.toMatch(/approval card/);
+ expect(by.remember.description).toMatch(/confirm with the user first/);
+ expect(by.remember.description).not.toMatch(/estimate/);
+ const est = (await rpc("tools/call", { name: "estimate_job", arguments: { tool: "add_captions", arguments: { video } } })) as { result: { structuredContent: { jobs: { modelId: string }[] }; isError: boolean } };
+ expect(est.result.isError).toBe(false);
+ expect(est.result.structuredContent.jobs.map((j) => j.modelId)).toEqual(["auto-subtitle"]);
+ expect(await rpc("tools/call", { name: "estimate_job", arguments: { tool: "remember", arguments: {} } })).toMatchObject({ result: { isError: true } });
+ // Without a chat, load_skill returns the instructions themselves.
+ const ls = (await rpc("tools/call", { name: "load_skill", arguments: { name: "narration" } })) as { result: { content: { text: string }[] } };
+ expect(ls.result.content[0].text).toMatch(/^# Narration \(\/narration\)/);
+ });
+});
+
+const video = "/api/files/uploads/2026-10-19/clip.mp4";
diff --git a/tests/assist-polish.test.ts b/tests/assist-polish.test.ts
new file mode 100644
index 00000000..8ac2f1bf
--- /dev/null
+++ b/tests/assist-polish.test.ts
@@ -0,0 +1,52 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { NextRequest } from "next/server";
+import { describe, expect, it } from "vitest";
+import { HUB_MODES } from "@/lib/hubs";
+// Plain .mjs helper shared with the Playwright scripts.
+import { dynamicSamples, hubModePaths, studioRoutes } from "./e2e/_routes.mjs";
+
+const root = process.cwd();
+// The proxy reads the sign-in settings from the data folder: use an empty one (no password).
+process.env.FUOBE_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-polish-"));
+
+describe("/apps/<unknown> is a real 404", () => {
+ it("the proxy rewrites unknown app ids to the not-found page with status 404", async () => {
+ delete process.env.FUOBE_PASSWORD;
+ const { proxy } = await import("@/proxy");
+ const unknown = proxy(new NextRequest("http://localhost:3000/apps/does-not-exist"));
+ expect(unknown.status).toBe(404);
+ expect(unknown.headers.get("x-middleware-rewrite")).toMatch(/\/_fuobe-not-found$/);
+ const known = proxy(new NextRequest("http://localhost:3000/apps/app-packshot"));
+ expect(known.status).toBe(200);
+ expect(known.headers.get("x-middleware-rewrite")).toBeNull();
+ expect(proxy(new NextRequest("http://localhost:3000/apps")).headers.get("x-middleware-rewrite")).toBeNull();
+ // A malformed escape doesn't crash the proxy.
+ expect(proxy(new NextRequest("http://localhost:3000/apps/%E0%A4%A")).status).toBe(404);
+ });
+});
+
+describe("the 390 px sweep visits dynamic routes", () => {
+ it("finds every dynamic route and has a sample for each", () => {
+ const { routes, patterns } = studioRoutes(root) as { routes: string[]; patterns: string[] };
+ expect(routes).toContain("/assist/skills");
+ expect(patterns).toEqual(expect.arrayContaining(["/audio/[mode]", "/video-tools/[mode]", "/upscale/[mode]", "/cinema/[id]", "/canvas/[id]", "/apps/[id]", "/assist/projects/[id]"]));
+ const { urls, unsampled } = dynamicSamples(root, { cinema: "c1", canvas: "v1", assistProject: "p1" }) as { urls: string[]; unsampled: string[] };
+ expect(unsampled).toEqual([]);
+ expect(urls).toEqual(expect.arrayContaining(["/cinema/c1", "/cinema/does-not-exist", "/canvas/v1", "/canvas/does-not-exist", "/assist/projects/p1", "/apps/does-not-exist"]));
+ });
+
+ it("reads every hub mode from src/lib/hubs.ts (the first mode is the hub's own page)", () => {
+ const expected = Object.entries(HUB_MODES).flatMap(([hub, modes]) => modes.slice(1).map((m) => `/${hub}/${m.id}`));
+ expect((hubModePaths(root) as string[]).sort()).toEqual(expected.sort());
+ });
+});
+
+describe("Cinema uses the shared live stream", () => {
+ it("opens no EventSource of its own", () => {
+ const src = fs.readFileSync(path.join(root, "src/components/cinema/hooks.ts"), "utf8");
+ expect(src).not.toMatch(/new EventSource/);
+ expect(src).toMatch(/useGenerationEvents/);
+ });
+});
diff --git a/tests/assist-skills.test.ts b/tests/assist-skills.test.ts
new file mode 100644
index 00000000..f0b06f79
--- /dev/null
+++ b/tests/assist-skills.test.ts
@@ -0,0 +1,325 @@
+import fs from "node:fs";
+import http from "node:http";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import {
+ contextUpdate,
+ factMap,
+ guessCategory,
+ parseFrontmatter,
+ parseMemoryImport,
+ parseSkillMd,
+ renderContext,
+ skillSlug,
+ slashQuery,
+ slashSkills,
+ toSkillMd,
+ type ContextFact,
+} from "@/lib/assist";
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-assist-skills-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+process.env.OLLAMA_URL = "http://127.0.0.1:9";
+
+const skills = await import("@/server/skills");
+const memory = await import("@/server/assist/memory");
+const projects = await import("@/server/assist/projects");
+const { zipStored, unzip } = await import("@/server/assist/unzip");
+const { createElement } = await import("@/server/elements");
+const { saveFile } = await import("@/server/storage");
+const agent = await import("@/server/assist/agent");
+
+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
+
+const md = (fm: string, body = "# Do it\n\n1. Step one.") => `---\n${fm}\n---\n\n${body}\n`;
+
+describe("SKILL.md parsing and validation", () => {
+ it("reads the frontmatter: quoted values, block scalars, lists and the offline map", () => {
+ const fm = parseFrontmatter(`name: product-photos
+title: "Product: photos"
+description: >
+ Studio photos
+ of products.
+when-to-use: |
+ Line one
+ Line two
+tags: [product, photo]
+offline:
+ kind: image
+ aspect: "1:1"
+ outputs: 4
+# a comment`);
+ expect(fm).toMatchObject({ name: "product-photos", title: "Product: photos", description: "Studio photos of products.", when_to_use: "Line one\nLine two", tags: ["product", "photo"] });
+ expect(fm.offline).toEqual({ kind: "image", aspect: "1:1", outputs: "4" });
+ });
+
+ it("accepts a valid skill and fills the title from the name", () => {
+ const r = parseSkillMd(md("name: recipe-reels\ndescription: Cooking reels from a recipe.\noffline:\n kind: video\n outputs: 9"));
+ expect(r.ok).toBe(true);
+ if (!r.ok) return;
+ expect(r.skill).toMatchObject({ name: "recipe-reels", title: "Recipe reels", description: "Cooking reels from a recipe.", whenToUse: "", offline: { kind: "video", outputs: 4 } });
+ expect(r.skill.body).toBe("# Do it\n\n1. Step one.");
+ });
+
+ it("names what's wrong, prefixed the way Supercomputer does", () => {
+ const err = (text: string) => {
+ const r = parseSkillMd(text);
+ return r.ok ? null : r.error;
+ };
+ expect(err("# no frontmatter")).toMatch(/^Check SKILL\.md and try again: it needs a frontmatter block/);
+ expect(err(md("description: x"))).toMatch(/has no name/);
+ expect(err(md("name: Product Photos\ndescription: x"))).toMatch(/isn't a valid name/);
+ expect(err(md("name: a--b\ndescription: x"))).toMatch(/isn't a valid name/);
+ expect(err(md("name: ok-name"))).toMatch(/no description/);
+ expect(err(md(`name: ok\ndescription: ${"x".repeat(1100)}`))).toMatch(/keep it under 1024/);
+ expect(err(md("name: ok\ndescription: x", ""))).toMatch(/no instructions/);
+ });
+
+ it("writes a skill back to SKILL.md that parses to the same skill", () => {
+ const s = { name: "a-b", title: "A: b", description: "Does a thing\nwell", whenToUse: "When asked", icon: "film", studio: "/video", tags: ["x", "y z"], body: "# Hi\n\nText" };
+ const r = parseSkillMd(toSkillMd(s));
+ expect(r.ok && r.skill).toMatchObject({ name: "a-b", title: "A: b", description: "Does a thing well", whenToUse: "When asked", icon: "film", studio: "/video", tags: ["x", "y z"], body: "# Hi\n\nText" });
+ });
+
+ it("makes names from titles", () => {
+ expect(skillSlug("Café Reels — 2026!")).toBe("cafe-reels-2026");
+ expect(skillSlug("!!!")).toBe("my-skill");
+ });
+});
+
+describe("/name in the composer", () => {
+ const known = (n: string) => ["product-photoshoot", "thumbnail-generation"].includes(n);
+ it("takes leading skill tokens off the message, leaving unknown ones in the text", () => {
+ expect(slashSkills("/product-photoshoot /thumbnail-generation a coffee ad", known)).toEqual({ skills: ["product-photoshoot", "thumbnail-generation"], text: "a coffee ad" });
+ expect(slashSkills("/nope do it", known)).toEqual({ skills: [], text: "/nope do it" });
+ expect(slashSkills("make /product-photoshoot", known)).toEqual({ skills: [], text: "make /product-photoshoot" });
+ expect(slashSkills("/product-photoshoot", known)).toEqual({ skills: ["product-photoshoot"], text: "" });
+ });
+ it("finds the /partial at the caret only at the start of the message", () => {
+ expect(slashQuery("/pro", 4)).toEqual({ start: 0, query: "pro" });
+ expect(slashQuery("/product-photoshoot /thu", 24)).toEqual({ start: 20, query: "thu" });
+ expect(slashQuery("hello /pro", 10)).toBeNull();
+ expect(slashQuery("/", 1)).toEqual({ start: 0, query: "" });
+ });
+});
+
+describe("memory import", () => {
+ it("reads headings, bullets, numbered items and category prefixes; drops boilerplate and duplicates", () => {
+ const items = parseMemoryImport(`Here is what I remember about you:
+
+## Preferences
+- Prefers vertical 9:16 videos
+- Prefers vertical 9:16 videos.
+1. Likes warm, filmic grading
+
+**Communication**
+* Wants short answers
+
+Tooling: Uses an RTX 4090 with ComfyUI
+- ok`);
+ expect(items).toEqual([
+ { category: "Preference", text: "Prefers vertical 9:16 videos" },
+ { category: "Preference", text: "Likes warm, filmic grading" },
+ { category: "Communication", text: "Wants short answers" },
+ { category: "Tooling", text: "Uses an RTX 4090 with ComfyUI" },
+ ]);
+ });
+ it("reads JSON exports too", () => {
+ expect(parseMemoryImport(JSON.stringify({ memories: [{ content: "Brand colour is teal #1E9E8F", category: "convention" }, "Call me Sam"] }))).toEqual([
+ { category: "Convention", text: "Brand colour is teal #1E9E8F" },
+ { category: "Communication", text: "Call me Sam" },
+ ]);
+ });
+ it("guesses categories from the words", () => {
+ expect(guessCategory("Always export 4:5 for Instagram")).toBe("Convention");
+ expect(guessCategory("My GPU has 12 GB of VRAM")).toBe("Environment");
+ expect(guessCategory("Keep replies brief")).toBe("Communication");
+ expect(guessCategory("The sky is blue")).toBe("Notes");
+ });
+});
+
+describe("context updates", () => {
+ const facts = (extra: ContextFact[] = []): ContextFact[] => [{ section: "now", key: "date", text: "Today is 2026-10-19." }, { section: "memory", key: "m1", text: "- (m1) [Preference] 9:16" }, ...extra];
+ it("renders sections and sends only what changed", () => {
+ expect(renderContext(facts())).toBe("## This chat\nToday is 2026-10-19.\n\n## Memory (what you know about the user)\n- (m1) [Preference] 9:16");
+ const sent = factMap(facts());
+ expect(contextUpdate(sent, facts())).toBeNull();
+ const next = [{ section: "now" as const, key: "date", text: "Today is 2026-10-20." }, { section: "active" as const, key: "katana", text: "### /katana — Katana\nDo it" }];
+ const u = contextUpdate(sent, next)!;
+ expect(u).toMatch(/^Context update/);
+ expect(u).toContain("Today is 2026-10-20.");
+ expect(u).toContain("### /katana — Katana");
+ expect(u).toContain("No longer applies: (m1) [Preference] 9:16");
+ expect(contextUpdate(factMap(next), [next[0]])).toContain("Stop following the /katana skill.");
+ });
+});
+
+describe("skills on the server", () => {
+ it("loads every built-in from skills/: 20, valid, unique, each with when-to-use and an icon", () => {
+ const list = skills.listSkills();
+ const builtin = list.filter((s) => s.source === "builtin");
+ expect(builtin).toHaveLength(20);
+ expect(new Set(builtin.map((s) => s.name)).size).toBe(20);
+ for (const s of builtin) {
+ expect(s.whenToUse, s.name).not.toBe("");
+ expect(s.icon, s.name).toBeTruthy();
+ expect(s.chars, s.name).toBeGreaterThan(600);
+ }
+ for (const n of ["product-photoshoot", "ugc-video", "short-film", "narration", "thumbnail-generation", "image-repurposer", "faceless-video", "video-repurposer", "character-sheet", "youtube-script", "video-montage", "katana", "brand-asset-creation", "marketing-studio-cards"]) {
+ expect(builtin.map((s) => s.name)).toContain(n);
+ }
+ // Studio links point at pages that exist.
+ for (const s of builtin) {
+ const route = s.studio!.split("?")[0].replace(/^\/apps\/.+$/, "/apps/[id]").replace(/^\/(audio|video-tools|upscale)\/.+$/, "/$1/[mode]");
+ const page = path.join(process.cwd(), "src/app/(studio)", route, "page.tsx");
+ expect(fs.existsSync(page), `${s.name} → ${s.studio}`).toBe(true);
+ }
+ });
+
+ it("creates, edits, duplicates, switches off and deletes the user's skills", () => {
+ expect(() => skills.createSkill({ name: "katana", title: "K", description: "d", body: "b" })).toThrow(/built-in skill/);
+ expect(() => skills.createSkill({ name: "upload", title: "U", description: "d", body: "b" })).toThrow(/reserved/);
+ expect(() => skills.createSkill({ name: "Bad Name", title: "B", description: "d", body: "b" })).toThrow(/valid name/);
+ const s = skills.createSkill({ name: "recipe-reels", title: "Recipe reels", description: "Cooking reels.", whenToUse: "A recipe", body: "# Steps", icon: "film" });
+ expect(s).toMatchObject({ source: "user", enabled: true, icon: "film" });
+ expect(() => skills.createSkill({ name: "recipe-reels", title: "x", description: "d", body: "b" })).toThrow(/already have/);
+ expect(skills.updateSkill("recipe-reels", { body: "# New steps", name: "recipe-videos" })).toMatchObject({ name: "recipe-videos", body: "# New steps" });
+ expect(skills.getSkill("recipe-reels")).toBeNull();
+ expect(() => skills.updateSkill("katana", { body: "x" })).toThrow(/can't be edited/);
+ expect(() => skills.deleteSkill("katana")).toThrow(/can't be deleted/);
+ const copy = skills.duplicateSkill("katana");
+ expect(copy).toMatchObject({ name: "katana-copy", source: "user", title: "Katana (copy)" });
+ expect(skills.setSkillEnabled("katana", false).enabled).toBe(false);
+ expect(skills.enabledSkills().some((x) => x.name === "katana")).toBe(false);
+ skills.setSkillEnabled("katana", true);
+ skills.deleteSkill("recipe-videos");
+ skills.deleteSkill("katana-copy");
+ expect(skills.listSkills().filter((x) => x.source === "user")).toHaveLength(0);
+ });
+
+ it("imports .zip / .skill archives with one SKILL.md and keeps the text files beside it", () => {
+ const skill = Buffer.from(md("name: zipped\ndescription: From a zip."));
+ const zip = zipStored([
+ { name: "zipped/SKILL.md", data: skill },
+ { name: "zipped/refs/style.md", data: Buffer.from("Use pastel colours.") },
+ { name: "zipped/logo.png", data: Buffer.from([0x89, 0x50, 0x4e, 0x47, 0, 1, 2]) },
+ { name: "__MACOSX/zipped/._SKILL.md", data: Buffer.from("junk") },
+ ]);
+ expect(unzip(zip).map((e) => e.name)).toContain("zipped/refs/style.md");
+ const r = skills.importSkill({ name: "zipped.skill", data: zip });
+ expect(r).toMatchObject({ replaced: false, skipped: ["logo.png"], skill: { name: "zipped", files: [{ path: "refs/style.md" }] } });
+ expect(skills.skillFile("zipped", "refs/style.md")).toBe("Use pastel colours.");
+ expect(skills.skillFile("zipped", "../../etc/passwd")).toBeNull();
+ expect(() => skills.importSkill({ name: "zipped.zip", data: zip })).toThrow(/already have/);
+ expect(skills.importSkill({ name: "zipped.zip", data: zip }, { replace: true }).replaced).toBe(true);
+ // A plain SKILL.md works too; broken archives and missing SKILL.md get a clear message.
+ expect(skills.importSkill({ name: "SKILL.md", data: Buffer.from(md("name: plain-md\ndescription: A file.")) }).skill.name).toBe("plain-md");
+ expect(() => skills.importSkill({ name: "x.zip", data: Buffer.from("not a zip") })).toThrow(/isn't a ZIP/);
+ expect(() => skills.importSkill({ name: "x.zip", data: zipStored([{ name: "a/readme.md", data: Buffer.from("hi") }]) })).toThrow(/no SKILL\.md/);
+ expect(() =>
+ skills.importSkill({ name: "two.zip", data: zipStored([{ name: "a/SKILL.md", data: skill }, { name: "b/SKILL.md", data: skill }]) }),
+ ).toThrow(/more than one skill/);
+ expect(() => skills.importSkill({ name: "k.zip", data: zipStored([{ name: "SKILL.md", data: Buffer.from(md("name: katana\ndescription: mine")) }]) })).toThrow(/built-in/);
+ expect(() => skills.importSkill({ name: "x.exe", data: Buffer.from("MZ") })).toThrow(/Upload a \.zip/);
+ });
+
+ it("caps what an archive may unpack to", () => {
+ const big = zipStored([{ name: "SKILL.md", data: Buffer.alloc(3_000_000, 65) }]);
+ expect(() => unzip(big)).toThrow(/over 2 MB/);
+ });
+});
+
+describe("memory", () => {
+ it("adds, dedupes, edits and deletes; project memories need their project", () => {
+ const a = memory.addMemory({ text: "Prefers vertical 9:16", category: "Preference" });
+ expect(a).toMatchObject({ scope: "personal", projectId: null, text: "Prefers vertical 9:16", source: "user" });
+ expect(memory.addMemory({ text: "prefers vertical 9:16!", category: "Convention" }).id).toBe(a.id);
+ expect(memory.listMemories({ scope: "personal" })).toHaveLength(1);
+ expect(memory.updateMemory(a.id, { text: "Prefers vertical 9:16 for Reels" }).text).toBe("Prefers vertical 9:16 for Reels");
+ expect(() => memory.addMemory({ text: "x", category: "Notes", scope: "project" })).toThrow(/needs its project/);
+ expect(() => memory.addMemory({ text: "x".repeat(600), category: "Notes" })).toThrow(/under 500/);
+ expect(() => memory.addMemory({ text: "x", category: "Nope" as never })).toThrow(/Pick a category/);
+ expect(memory.deleteMemory(a.id)).toBe(true);
+ expect(memory.deleteMemory(a.id)).toBe(false);
+ });
+
+ it("imports in bulk without duplicates, and keeps project memory inside its project", () => {
+ const p = projects.createProject({ name: "Mem project", usePersonalMemory: false });
+ expect(memory.importMemories([{ text: "Personal one", category: "Notes" }, { text: "Personal one", category: "Notes" }], "personal", null)).toEqual({ added: 1, skipped: 1 });
+ memory.addMemory({ text: "Only for this project", category: "Convention", projectId: p.id });
+ expect(memory.memoriesFor(p.id, false).map((m) => m.text)).toEqual(["Only for this project"]);
+ expect(memory.memoriesFor(p.id, true).map((m) => m.text)).toEqual(["Only for this project", "Personal one"]);
+ expect(memory.memoriesFor(null).map((m) => m.text)).toEqual(["Personal one"]);
+ });
+});
+
+describe("projects", () => {
+ let server: http.Server;
+ let base = "";
+ beforeAll(async () => {
+ process.env.FUOBE_ALLOW_PRIVATE_URLS = "1";
+ server = http.createServer((req, res) => {
+ if (req.url === "/brand") {
+ res.setHeader("content-type", "text/html; charset=utf-8");
+ res.end(`<html><head><title>Oatly-ish &amp; Co</title><meta name="description" content="Oat milk, playfully."><style>.x{}</style></head><body><nav>Menu</nav><h1>About us</h1><p>We make oat milk.</p><script>evil()</script><ul><li>Teal</li><li>Cream</li></ul></body></html>`);
+ } else if (req.url === "/image") {
+ res.setHeader("content-type", "image/png");
+ res.end(Buffer.from([0x89, 0x50]));
+ } else {
+ res.statusCode = 404;
+ res.end("no");
+ }
+ });
+ await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));
+ base = `http://127.0.0.1:${(server.address() as { port: number }).port}`;
+ });
+ afterAll(() => {
+ server.close();
+ delete process.env.FUOBE_ALLOW_PRIVATE_URLS;
+ });
+
+ it("reads pages as text: title, description, body without scripts, styles or navigation", () => {
+ expect(projects.htmlToText('<title>A &amp; B</title><body><nav>x</nav><p>One</p><script>no()</script><p>Two&nbsp;&#8212; three</p></body>')).toEqual({ title: "A & B", text: "One\nTwo — three" });
+ });
+
+ it("adds links, files, elements and notes, up to 20, and refetches a link", async () => {
+ const p = projects.createProject({ name: "Spring", instructions: "Pastel, 9:16.", color: "rose", skills: ["product-photoshoot"] });
+ const link = await projects.addSource(p.id, { kind: "link", url: `${base}/brand` });
+ expect(link).toMatchObject({ kind: "link", status: "ready", title: "Oatly-ish & Co" });
+ expect(link.excerpt).toContain("We make oat milk.");
+ expect(link.excerpt).not.toMatch(/evil|Menu/);
+ const bad = await projects.addSource(p.id, { kind: "link", url: `${base}/image` });
+ expect(bad).toMatchObject({ status: "error" });
+ expect(bad.error).toMatch(/upload it instead/);
+ const missing = await projects.addSource(p.id, { kind: "link", url: `${base}/gone` });
+ expect(missing.status).toBe("error");
+ expect((await projects.refreshSource(p.id, missing.id)).status).toBe("error");
+ const txt = saveFile({ data: Buffer.from("Line 1\nLine 2"), contentType: "text/plain", name: "brief.txt", source: "upload" });
+ expect(await projects.addSource(p.id, { kind: "file", url: txt.url, name: "brief.txt" })).toMatchObject({ kind: "file", status: "ready", excerpt: "Line 1\nLine 2" });
+ const png = saveFile({ data: Buffer.from([0x89, 0x50, 0x4e, 0x47]), contentType: "image/png", source: "upload" });
+ expect(await projects.addSource(p.id, { kind: "file", url: png.url })).toMatchObject({ kind: "image", url: png.url });
+ const el = createElement({ name: "Maya", kind: "character", description: "Our mascot", references: [png.url] });
+ expect(await projects.addSource(p.id, { kind: "element", elementId: el.id })).toMatchObject({ kind: "element", title: "Maya", elementId: el.id });
+ const note = await projects.addSource(p.id, { kind: "text", text: "Brand voice\nPlayful." });
+ expect(note).toMatchObject({ kind: "text", title: "Brand voice" });
+ expect(projects.sourceText(p.id, note.id)?.text).toBe("Brand voice\nPlayful.");
+ for (let i = projects.getProject(p.id)!.sources.length; i < 20; i++) await projects.addSource(p.id, { kind: "text", text: `Note ${i}` });
+ await expect(projects.addSource(p.id, { kind: "text", text: "21st" })).rejects.toThrow(/up to 20 sources/);
+ expect(projects.deleteSource(p.id, note.id)).toBe(true);
+ expect(projects.getProject(p.id)!.sources).toHaveLength(19);
+ });
+
+ it("deleting a project keeps its chats as personal chats and drops its memory", () => {
+ const p = projects.createProject({ name: "Doomed" });
+ const t = agent.createThread({ engine: "cloud", agent: "offline", projectId: p.id });
+ memory.addMemory({ text: "Doomed memory", category: "Notes", projectId: p.id });
+ expect(projects.getProject(p.id)!.chats).toBe(1);
+ expect(agent.listThreads({ project: p.id }).map((x) => x.id)).toEqual([t.id]);
+ expect(projects.deleteProject(p.id)).toBe(true);
+ expect(agent.getThread(t.id)!.thread.projectId).toBeNull();
+ expect(agent.listThreads({ project: null }).map((x) => x.id)).toContain(t.id);
+ expect(memory.listMemories({ scope: "project", projectId: p.id })).toHaveLength(0);
+ });
+});
diff --git a/tests/e2e/_routes.mjs b/tests/e2e/_routes.mjs
new file mode 100644
index 00000000..2c5c5250
--- /dev/null
+++ b/tests/e2e/_routes.mjs
@@ -0,0 +1,60 @@
+// Which URLs the browser checks visit: every page under src/app/(studio), with sample values for
+// the dynamic segments. Pure (file system only) so vitest can check it too.
+import fs from "node:fs";
+import path from "node:path";
+
+/** Static routes ("/", "/assist/skills") and dynamic patterns ("/cinema/[id]") under (studio). */
+export function studioRoutes(root) {
+ const base = path.join(root, "src/app/(studio)");
+ const routes = [];
+ const patterns = [];
+ const walk = (dir, url, dynamic) => {
+ if (fs.existsSync(path.join(dir, "page.tsx"))) (dynamic ? patterns : routes).push(url || "/");
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
+ if (!e.isDirectory()) continue;
+ const seg = e.name;
+ if (seg.startsWith("(")) walk(path.join(dir, seg), url, dynamic);
+ else walk(path.join(dir, seg), `${url}/${seg}`, dynamic || seg.startsWith("["));
+ }
+ };
+ walk(base, "", false);
+ return { routes: routes.sort(), patterns: patterns.sort() };
+}
+
+/** Every mode path of the studio hubs (/audio/music, /video-tools/join…), read from src/lib/hubs.ts. */
+export function hubModePaths(root) {
+ const src = fs.readFileSync(path.join(root, "src/lib/hubs.ts"), "utf8");
+ const block = /HUB_MODES[^=]*=\s*\{([\s\S]*?)\n\};/.exec(src)?.[1] ?? "";
+ const out = [];
+ for (const m of block.matchAll(/["']?([\w-]+)["']?:\s*\[([\s\S]*?)\]/g)) {
+ const ids = [...m[2].matchAll(/id:\s*"([\w-]+)"/g)].map((x) => x[1]);
+ // The first mode is the hub's own page; the others have their own path.
+ for (const id of ids.slice(1)) out.push(`/${m[1]}/${id}`);
+ }
+ return out;
+}
+
+/**
+ * Sample URLs for the dynamic patterns. `ids` holds ids created for the run (cinema, canvas,
+ * assistProject). Unknown ids are included on purpose: their not-found pages must fit too.
+ */
+export function dynamicSamples(root, ids = {}) {
+ const samples = {
+ "/apps/[id]": ["/apps/app-face-swap", "/apps/app-packshot", "/apps/does-not-exist"],
+ "/elements/[id]": ["/elements/does-not-exist"],
+ "/cinema/[id]": [ids.cinema && `/cinema/${ids.cinema}`, "/cinema/does-not-exist"],
+ "/canvas/[id]": [ids.canvas && `/canvas/${ids.canvas}`, "/canvas/does-not-exist"],
+ "/assist/projects/[id]": [ids.assistProject && `/assist/projects/${ids.assistProject}`, "/assist/projects/does-not-exist"],
+ };
+ const hubs = hubModePaths(root);
+ const { patterns } = studioRoutes(root);
+ const urls = [];
+ const unsampled = [];
+ for (const p of patterns) {
+ const hub = /^\/([\w-]+)\/\[mode\]$/.exec(p);
+ const list = hub ? hubs.filter((h) => h.startsWith(`/${hub[1]}/`)) : (samples[p] ?? []).filter(Boolean);
+ if (!list.length) unsampled.push(p);
+ urls.push(...list);
+ }
+ return { urls, unsampled };
+}
diff --git a/tests/e2e/no-horizontal-scroll.mjs b/tests/e2e/no-horizontal-scroll.mjs
index 06901f06..b4c08553 100644
--- a/tests/e2e/no-horizontal-scroll.mjs
+++ b/tests/e2e/no-horizontal-scroll.mjs
@@ -3,49 +3,33 @@
// (pnpm test:e2e:mobile; the app must be running, demo mode is fine). Exits 1 if any page is wider
// than the screen or doesn't load.
//
-// Every page under src/app/(studio) is visited, dynamic segments with a sample id (a cinema project and
-// a canvas are created for the purpose), plus /login and an unknown URL (the 404 page). For each route it
+// Every page under src/app/(studio) is visited, dynamic segments with samples from tests/e2e/_routes.mjs:
+// every studio hub mode (/audio/music, /video-tools/join…), real ids (a cinema project, a canvas and an
+// Assist project are created for the purpose) and unknown ids (their not-found pages must fit too),
+// plus /login and an unknown URL (the 404 page). A dynamic route without a sample is named. For each route it
// asserts document.documentElement.scrollWidth === clientWidth once the page has rendered, and names
// the widest elements when it isn't. Pages that don't load are reported apart from layout failures.
-import fs from "node:fs";
-import path from "node:path";
import { launch, openRoute, PHONE, post, root } from "./_browser.mjs";
+import { dynamicSamples, studioRoutes } from "./_routes.mjs";
const args = process.argv.slice(2);
const app = (args.find((a) => !a.startsWith("--")) ?? "http://localhost:3000").replace(/\/$/, "");
const schemes = args.includes("--dark") ? ["dark"] : args.includes("--light") ? ["light"] : ["light", "dark"];
const only = args.find((a) => a.startsWith("--routes="))?.slice(9).split(",").filter(Boolean);
-/** Static routes from the file system, plus samples for the dynamic ones. */
+/** Static routes from the file system, plus samples for the dynamic ones (hub modes, created ids, unknown ids). */
async function discoverRoutes() {
- const base = path.join(root, "src/app/(studio)");
- const out = [];
- const walk = (dir, url) => {
- for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
- if (!e.isDirectory()) continue;
- const seg = e.name;
- if (seg.startsWith("(")) walk(path.join(dir, seg), url);
- else if (seg.startsWith("[")) continue; // sampled below
- else walk(path.join(dir, seg), `${url}/${seg}`);
- }
- if (fs.existsSync(path.join(dir, "page.tsx"))) out.push(url || "/");
- };
- walk(base, "");
+ const { routes: out } = studioRoutes(root);
const project = await post(app, "/api/cinema/projects", { name: "Layout check" });
const canvas = await post(app, "/api/canvases", { name: "Layout check" });
- const samples = [
- "/apps/app-face-swap",
- "/apps/app-packshot",
- "/elements/does-not-exist",
- "/library?tab=favorites",
- project?.id ? `/cinema/${project.id}` : null,
- canvas?.id ? `/canvas/${canvas.id}` : null,
- "/login",
- "/this-page-does-not-exist",
- ].filter(Boolean);
- if (!project?.id) console.log("note: couldn't create a sample cinema project, /cinema/[id] is not checked");
- if (!canvas?.id) console.log("note: couldn't create a sample canvas, /canvas/[id] is not checked");
- return [...new Set([...out.sort(), ...samples])];
+ const assistProject = await post(app, "/api/assist/projects", { name: "Layout check" });
+ const { urls, unsampled } = dynamicSamples(root, { cinema: project?.id, canvas: canvas?.id, assistProject: assistProject?.id });
+ const samples = [...urls, "/library?tab=favorites", "/login", "/this-page-does-not-exist"];
+ if (!project?.id) console.log("note: couldn't create a sample cinema project, only an unknown /cinema/[id] is checked");
+ if (!canvas?.id) console.log("note: couldn't create a sample canvas, only an unknown /canvas/[id] is checked");
+ if (!assistProject?.id) console.log("note: couldn't create a sample Assist project, only an unknown /assist/projects/[id] is checked");
+ for (const p of unsampled) console.log(`note: ${p} has no sample in tests/e2e/_routes.mjs, so it isn't checked`);
+ return [...new Set([...out, ...samples])];
}
const routes = only ?? (await discoverRoutes());