The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Fixes 5: Settings → Training has the AI-Toolkit URL the training messages ask for
Claude5a7037595593
diff --git a/src/app/api/providers/test/route.ts b/src/app/api/providers/test/route.tsindex 989b31cf..59206797 100644--- a/src/app/api/providers/test/route.ts+++ b/src/app/api/providers/test/route.ts@@ -1,5 +1,6 @@import { candidateValues, isTestProvider, PROVIDER_SETTINGS, settingProblem } from "@/lib/connections";import { testCivitaiKey } from "@/server/loras";+import { testAiToolkit } from "@/server/training";import { PROVIDERS } from "@/server/providers";import { validateSetting, withCandidates, type SettingName } from "@/server/settings";@@ -13,8 +14,9 @@ import { validateSetting, withCandidates, type SettingName } from "@/server/settexport async function POST(request: Request) {const body = (await request.json().catch(() => ({}))) as { provider?: unknown; value?: unknown; values?: unknown; field?: unknown };const provider = body.provider;- // The civitai key isn't a model provider's: it downloads LoRAs.- const adapter = provider === "civitai" ? { test: testCivitaiKey } : isTestProvider(provider) ? PROVIDERS[provider as Exclude<typeof provider, "civitai">] : undefined;+ // The civitai key isn't a model provider's (it downloads LoRAs), nor is AI-Toolkit (it trains them).+ const adapter =+ provider === "civitai" ? { test: testCivitaiKey } : provider === "ai-toolkit" ? { test: testAiToolkit } : isTestProvider(provider) ? PROVIDERS[provider as Exclude<typeof provider, "civitai" | "ai-toolkit">] : undefined;if (!isTestProvider(provider) || !adapter?.test) return Response.json({ ok: false, detail: "Unknown provider" }, { status: 400 });const values = candidateValues(provider, body.values, body.value) as Partial<Record<SettingName, string>>;try {diff --git a/src/components/assist/mode-picker.tsx b/src/components/assist/mode-picker.tsxindex 4fa1477e..8b9efc70 100644--- a/src/components/assist/mode-picker.tsx+++ b/src/components/assist/mode-picker.tsx@@ -204,7 +204,7 @@ export function ModePicker({{smartOff && (<p className="mt-2 px-1 text-[12px] text-warning">Smart and the Claude models need an Anthropic API key —{" "}- <Link href="/settings#keys" className="underline underline-offset-2">+ <Link href="/settings#text-ai" className="underline underline-offset-2">add one in Settings</Link>.diff --git a/src/components/command-palette.tsx b/src/components/command-palette.tsxindex ff7eb11d..662a21e1 100644--- a/src/components/command-palette.tsx+++ b/src/components/command-palette.tsx@@ -1,7 +1,7 @@"use client";import { useQuery } from "@tanstack/react-query";-import { Bell, Clapperboard, Cpu, Film, KeyRound, Layers, LayoutGrid, Loader2, Play, Plug, Plus, Scale, Server, Settings2, ShieldCheck, Sparkles, Wand2, type LucideIcon } from "lucide-react";+import { Bell, Clapperboard, Cpu, Film, GraduationCap, KeyRound, Layers, LayoutGrid, Loader2, Play, Plug, Plus, Scale, Server, Settings2, ShieldCheck, Sparkles, Wand2, type LucideIcon } from "lucide-react";import { useRouter } from "next/navigation";import { createContext, lazy, Suspense, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";import { useSkills } from "@/components/assist/hooks";@@ -52,6 +52,7 @@ const SETTINGS: { id: string; label: string; icon: LucideIcon; keywords: string;{ id: "comfyui", label: "ComfyUI server", icon: Server, keywords: "open source gpu url connect local" },{ id: "engine", label: "Engine mode", icon: Cpu, keywords: "open source cloud both" },{ id: "loras", label: "LoRAs", icon: Layers, keywords: "lora folder civitai key looks motions effects download licence" },+ { id: "training", label: "Training (AI-Toolkit)", icon: GraduationCap, keywords: "ai-toolkit aitk train lora soul id gpu url token" },{id: "models",label: "Models & licences",diff --git a/src/components/moodboards/train-board.tsx b/src/components/moodboards/train-board.tsxindex 1dbf8755..82a0b452 100644--- a/src/components/moodboards/train-board.tsx+++ b/src/components/moodboards/train-board.tsx@@ -81,7 +81,7 @@ export function TrainBoardDialog({ board, open, onOpenChange }: { board: Moodboa{(t.blocker || t.demo) && (<p className="mt-2 text-[12px] text-muted-foreground">{t.blocker ?? (t.provider === "fal" ? "No fal.ai key yet: this runs as a demo and trains nothing." : "No AI-Toolkit set up yet: this runs as a demo and trains nothing.")}{" "}- <Link href="/settings#training" className="text-brand-text underline underline-offset-2">+ <Link href={t.provider === "fal" ? "/settings#fal" : "/settings#training"} className="text-brand-text underline underline-offset-2">Open Settings</Link></p>diff --git a/src/components/settings-form.tsx b/src/components/settings-form.tsxindex 974b114c..94a4c907 100644--- a/src/components/settings-form.tsx+++ b/src/components/settings-form.tsx@@ -13,7 +13,7 @@ import { ConnectField, useSettings } from "@/components/connect-field";import { GetStarted } from "@/components/get-started";import { LoraSettings } from "@/components/lora-settings";import { useStatus, type StatusInfo } from "@/lib/api";-import { connectionSummary, ENGINE_MODE_LABEL, FAL_KEYS_URL, showFirstRun } from "@/lib/connections";+import { AI_TOOLKIT_REPO, connectionSummary, DEFAULT_AI_TOOLKIT_URL, ENGINE_MODE_LABEL, FAL_KEYS_URL, showFirstRun } from "@/lib/connections";import { cn } from "@/lib/utils";import { ConnectorSettings } from "@/components/assist/connectors-settings";import { NotificationSettings } from "@/components/notification-settings";@@ -342,6 +342,39 @@ export function SettingsForm({ prices }: { prices?: string }) {<LoraSettings folder={get("comfyLorasDir")} civitaiKey={get("civitaiKey")} /></Section>+ <Section+ id="training"+ title="Training · AI-Toolkit"+ description={+ <>+ Train Soul IDs and Fuobe looks (LoRAs) on your own GPU with{" "}+ <a href={AI_TOOLKIT_REPO} target="_blank" rel="noreferrer" className="text-brand-text underline-offset-2 hover:underline">+ AI-Toolkit+ </a>+ : free, and the file stays yours. Without it, train in the cloud on fal.ai, or download a training kit from the Train dialog.+ </>+ }+ inactive={mode === "cloud" ? "Not used in Paid APIs only mode" : undefined}+ >+ <ConnectField+ name="aiToolkitUrl"+ setting={get("aiToolkitUrl")}+ provider="ai-toolkit"+ label="AI-Toolkit URL"+ placeholder={DEFAULT_AI_TOOLKIT_URL}+ hint="Where AI-Toolkit's UI listens (in ai-toolkit/ui: npm run build_and_start). Test checks it answers."+ />+ <ConnectField name="aiToolkitToken" setting={get("aiToolkitToken")} provider="ai-toolkit" label="Auth token (optional)" hint="The AI_TOOLKIT_AUTH the trainer was started with, if any." />+ <ConnectField+ name="aiToolkitDatasetDir"+ setting={get("aiToolkitDatasetDir")}+ provider="ai-toolkit"+ label="Photos folder (optional)"+ placeholder="/mnt/shared/datasets"+ hint="Where Fuobe writes the training photos. Blank: Fuobe's data folder, for an AI-Toolkit on this machine; on another machine, a folder both can read."+ />+ </Section>+<Sectionid="text-ai"title="Prompt enhancement · Claude or Ollama"diff --git a/src/components/train-dialog.tsx b/src/components/train-dialog.tsxindex 62946435..69cb6683 100644--- a/src/components/train-dialog.tsx+++ b/src/components/train-dialog.tsx@@ -201,7 +201,7 @@ export function TrainDialog({ element, open, onOpenChange }: { element: StudioEl<p className="mt-2 text-[12px] text-muted-foreground">{t.blocker ??`${t.provider === "fal" ? "No fal.ai key yet" : "No AI-Toolkit set up yet"}: this runs as a demo and trains nothing${hasFamily(f) ? ", and the Soul ID you trained stays" : ""}.`}{" "}- <Link href="/settings" className="text-brand-text underline underline-offset-2">+ <Link href={t.provider === "fal" ? "/settings#fal" : "/settings#training"} className="text-brand-text underline underline-offset-2">Open Settings</Link></p>diff --git a/src/lib/connections.ts b/src/lib/connections.tsindex ef08214a..ba1dfadf 100644--- a/src/lib/connections.ts+++ b/src/lib/connections.ts@@ -4,7 +4,7 @@* address looks like, when to offer the first-run guide, and each connection's one-line status.*/-export type TestProvider = "fal" | "replicate" | "comfyui" | "llm" | "civitai";+export type TestProvider = "fal" | "replicate" | "comfyui" | "llm" | "civitai" | "ai-toolkit";/** The settings each provider's connection test reads; an unsaved value for one of them can be tested before it's saved. */export const PROVIDER_SETTINGS = {@@ -14,6 +14,8 @@ export const PROVIDER_SETTINGS = {llm: ["anthropicKey", "ollamaUrl", "ollamaModel", "enhanceProvider"],// Not a model provider: the key that downloads a recipe's civitai LoRAs (Settings → LoRAs).civitai: ["civitaiKey"],+ // Not a model provider either: the trainer Soul IDs and Fuobe looks train on, on your GPU (Settings → Training).+ "ai-toolkit": ["aiToolkitUrl", "aiToolkitToken", "aiToolkitDatasetDir"],} as const satisfies Record<TestProvider, readonly string[]>;export type ConnectionSetting = (typeof PROVIDER_SETTINGS)[TestProvider][number];@@ -45,6 +47,9 @@ export const FUOBE_REPO = "https://github.com/workingprototype/fuobe";/** How to install ComfyUI with every node pack Fuobe's workflows use. */export const COMFY_INSTALL_DOCS = `${FUOBE_REPO}/blob/main/scripts/comfy/README.md`;export const COMFY_INSTALL_COMMAND = "bash scripts/comfy/install-comfyui.sh";+/** The address AI-Toolkit's UI (ostris/ai-toolkit) listens on, and where to get it. */+export const DEFAULT_AI_TOOLKIT_URL = "http://127.0.0.1:8675";+export const AI_TOOLKIT_REPO = "https://github.com/ostris/ai-toolkit";/** key_id:key_secret, both halves present and no spaces. */const KEY_PAIR = /^[^\s:]+:[^\s:]+$/;@@ -79,6 +84,10 @@ export function settingProblem(name: string, raw: string): string | null {return addressProblem(v, "http://127.0.0.1:8189");case "ollamaUrl":return addressProblem(v, "http://127.0.0.1:11434");+ case "aiToolkitUrl":+ return addressProblem(v, DEFAULT_AI_TOOLKIT_URL);+ case "aiToolkitDatasetDir":+ return v.startsWith("/") || /^[A-Za-z]:[\\/]/.test(v) ? null : "Use a full path, like /mnt/shared/datasets";}return null;}diff --git a/src/server/training.ts b/src/server/training.tsindex cc65fd96..1d1bb683 100644--- a/src/server/training.ts+++ b/src/server/training.ts@@ -26,12 +26,13 @@ import {type TrainingTarget,} from "@/lib/catalog/training";import { TRAINING_REPLACED_BY } from "@/lib/catalog/replaced";+import { DEFAULT_AI_TOOLKIT_URL } from "@/lib/connections";import { DATA_DIR, db } from "./db";import { getElement, updateElement } from "./elements";import { keepTrainedLora, lorasPath, ownCopy, recordTrainedMirror } from "./loras";import { falFetch, falProvider } from "./providers/fal";import { ProviderError } from "./providers/types";-import { engineMode, getSetting } from "./settings";+import { engineMode, getSetting, isCandidate, savedSetting } from "./settings";import { readRef } from "./storage";import { zip } from "./zip";@@ -147,7 +148,7 @@ export function trainingBlocker(t: TrainingTarget): string | null {return `${fam.name} runs only ${mode === "open" ? "in the cloud" : "on your GPU"}, which this install turned off (Settings → ${ENGINE_MODE})`;}if (t.provider === "fal" && !getSetting("falKey")) return "Add a fal.ai key in Settings";- if (t.provider === "ai-toolkit" && !getSetting("aiToolkitUrl")) return "Set your AI-Toolkit URL in Settings (or download the training kit)";+ if (t.provider === "ai-toolkit" && !getSetting("aiToolkitUrl")) return "Set your AI-Toolkit URL in Settings → Training (or download the training kit)";return null;}@@ -282,18 +283,78 @@ async function dataset(el: StudioElement, trigger: string, images: string[]) {return { files, caption };}+const aitkBase = () => getSetting("aiToolkitUrl").replace(/\/+$/, "");++/**+ * Save & test of an AI-Toolkit address that isn't the saved one: the saved auth token stays with the trainer it was+ * saved for (as ComfyUI's does). Only a token typed for the test goes to the new address.+ */+const aitkTokenWithheld = () => isCandidate("aiToolkitUrl") && !isCandidate("aiToolkitToken") && aitkBase() !== savedSetting("aiToolkitUrl").replace(/\/+$/, "");++function aitkAuth(): Record<string, string> {+ const token = aitkTokenWithheld() ? "" : getSetting("aiToolkitToken");+ return token ? { Authorization: `Bearer ${token}` } : {};+}+async function aitk(pathname: string, init: RequestInit = {}) {- const base = getSetting("aiToolkitUrl").replace(/\/$/, "");- const token = getSetting("aiToolkitToken");- const res = await fetch(`${base}${pathname}`, {+ const res = await fetch(`${aitkBase()}${pathname}`, {...init,- headers: { "Content-Type": "application/json", ...(token ? { Authorization: `Bearer ${token}` } : {}), ...(init.headers ?? {}) },+ headers: { "Content-Type": "application/json", ...aitkAuth(), ...(init.headers ?? {}) },});const body = await res.json().catch(() => null);if (!res.ok) throw new ProviderError(`AI-Toolkit ${res.status}: ${JSON.stringify(body).slice(0, 300)}`, res.status);return body as Record<string, unknown>;}+/** Where Fuobe writes the training photos for AI-Toolkit: Settings' folder, else its own data folder (same machine). */+const datasetRoot = () => getSetting("aiToolkitDatasetDir") || path.join(DATA_DIR, "datasets");++/**+ * Settings → Training → Save & test. The address: AI-Toolkit's UI answers its job list (GET /api/jobs, with the auth+ * token when the trainer sets AI_TOOLKIT_AUTH). The photos folder: Fuobe can write there (checked without making it).+ */+export async function testAiToolkit(opts?: { focus?: string }): Promise<{ ok: boolean; detail: string }> {+ if (opts?.focus === "aiToolkitDatasetDir") return testDatasetDir();+ const base = aitkBase();+ if (!base) return { ok: false, detail: `No AI-Toolkit URL set — its UI listens on ${DEFAULT_AI_TOOLKIT_URL}` };+ let res: Response;+ try {+ res = await fetch(`${base}/api/jobs?only_active=true`, { headers: aitkAuth(), signal: AbortSignal.timeout(10_000) });+ } catch (e) {+ const why = (e as Error).name === "TimeoutError" ? "no answer in 10 s" : (e as Error).message;+ return { ok: false, detail: `Can't reach AI-Toolkit at ${base} (${why}). Is its UI running? (in ai-toolkit/ui: npm run build_and_start)` };+ }+ if (res.status === 401) {+ if (aitkTokenWithheld() && getSetting("aiToolkitToken")) {+ return { ok: false, detail: `AI-Toolkit wants its auth token: type it with the new address (the saved one stays with ${savedSetting("aiToolkitUrl").replace(/\/+$/, "")})` };+ }+ return { ok: false, detail: getSetting("aiToolkitToken") ? "AI-Toolkit rejected the auth token (401)" : "AI-Toolkit wants its auth token (AI_TOOLKIT_AUTH on the trainer): add it under Auth token" };+ }+ if (!res.ok) return { ok: false, detail: `AI-Toolkit answered HTTP ${res.status}` };+ const jobs = ((await res.json().catch(() => null)) as { jobs?: unknown } | null)?.jobs;+ if (!Array.isArray(jobs)) return { ok: false, detail: `Something answers at ${base}, but it isn't AI-Toolkit's UI (port 8675 by default)` };+ return { ok: true, detail: jobs.length ? `AI-Toolkit · ${jobs.length} training${jobs.length > 1 ? "s" : ""} running` : "AI-Toolkit · ready, no training running" };+}++/** Whether Fuobe can write the training photos to the folder (its nearest existing folder, when it isn't made yet). */+function testDatasetDir(): { ok: boolean; detail: string } {+ const set = getSetting("aiToolkitDatasetDir");+ const root = datasetRoot();+ if (!path.isAbsolute(root)) return { ok: false, detail: "Use a full path, like /mnt/shared/datasets" };+ let at = root;+ while (!fs.existsSync(at) && path.dirname(at) !== at) at = path.dirname(at);+ try {+ if (!fs.statSync(at).isDirectory()) throw new Error(`${at} is a file`);+ fs.accessSync(at, fs.constants.W_OK);+ } catch (e) {+ return { ok: false, detail: `Fuobe can't write to ${root} (${(e as NodeJS.ErrnoException).code ?? (e as Error).message})` };+ }+ return {+ ok: true,+ detail: set ? `Fuobe writes the training photos to ${root}: AI-Toolkit has to read the same folder` : `Fuobe writes the training photos to ${root} (its data folder), for an AI-Toolkit on this machine`,+ };+}+/** The fal queue URL of a trainer endpoint. */export const falQueueUrl = (endpoint: string) => `https://queue.fal.run/${endpoint}`;@@ -319,7 +380,7 @@ async function submit(id: string, el: StudioElement, t: TrainingTarget, trigger:}// AI-Toolkit: write the dataset where the trainer can read it, then create and start a job.- const root = getSetting("aiToolkitDatasetDir") || path.join(DATA_DIR, "datasets");+ const root = datasetRoot();const folder = path.join(root, `fuobe-${el.id}-${id}`);const { files } = await dataset(el, trigger, images);fs.mkdirSync(folder, { recursive: true });@@ -449,8 +510,8 @@ async function pollOne(r: Row) {return done(r,added- ? "Demo: no LoRA was trained. Add a fal.ai key or your AI-Toolkit in Settings, then train again"- : `Demo: no LoRA was trained, so the ${fam} Soul ID you trained before stays. Add a fal.ai key or your AI-Toolkit in Settings to retrain`,+ ? "Demo: no LoRA was trained. Add a fal.ai key, or your AI-Toolkit in Settings → Training, then train again"+ : `Demo: no LoRA was trained, so the ${fam} Soul ID you trained before stays. Add a fal.ai key, or your AI-Toolkit in Settings → Training, to retrain`,);}diff --git a/tests/connections.test.ts b/tests/connections.test.tsindex dc7e9652..5be873c3 100644--- a/tests/connections.test.ts+++ b/tests/connections.test.ts@@ -65,6 +65,10 @@ describe("key and address checks", () => {expect(settingProblem("ollamaUrl", "ftp://box")).toMatch(/http:\/\//);expect(settingProblem("comfyUrl", "not a url")).toMatch(/isn't a web address/);expect(settingProblem("ollamaModel", "anything")).toBeNull();+ expect(settingProblem("aiToolkitUrl", "127.0.0.1:8675")).toBe("Add http:// in front: http://127.0.0.1:8675");+ expect(settingProblem("aiToolkitUrl", "http://gpu-box:8675")).toBeNull();+ expect(settingProblem("aiToolkitDatasetDir", "datasets")).toMatch(/full path/);+ expect(settingProblem("aiToolkitDatasetDir", "/mnt/shared/datasets")).toBeNull();});it("keeps a test's unsaved values to the settings that provider reads", () => {@@ -74,6 +78,9 @@ describe("key and address checks", () => {expect(candidateValues("fal", undefined, " a:b ")).toEqual({ falKey: "a:b" });expect(candidateValues("comfyui", { comfyUrl: "http://x:8188", falKey: "no", comfyToken: 5 })).toEqual({ comfyUrl: "http://x:8188" });expect(candidateValues("llm", { ollamaModel: "llama3" })).toEqual({ ollamaModel: "llama3" });+ expect(isTestProvider("ai-toolkit")).toBe(true);+ expect(candidateValues("ai-toolkit", undefined, " http://gpu:8675 ")).toEqual({ aiToolkitUrl: "http://gpu:8675" });+ expect(candidateValues("ai-toolkit", { aiToolkitToken: "t", comfyUrl: "x" })).toEqual({ aiToolkitToken: "t" });});});@@ -236,6 +243,64 @@ describe("POST /api/providers/test with unsaved values", () => {expect(getSetting("anthropicKey")).toBe("");});+ it("tests an AI-Toolkit address (Soul ID's GPU trainer) before it's saved: its UI's job list, with the auth token it wants", async () => {+ const jobs = (n: number) => ({ jobs: Array.from({ length: n }, (_, i) => ({ id: `j${i}`, status: "running" })) });+ const ready = await withFetch({ "http://10.0.0.7:8675/api/jobs": [200, jobs(0)] }, () => post({ provider: "ai-toolkit", value: "http://10.0.0.7:8675/" }));+ expect(ready.result.body).toEqual({ ok: true, detail: "AI-Toolkit · ready, no training running" });+ expect(ready.seen).toEqual([{ url: "http://10.0.0.7:8675/api/jobs?only_active=true", auth: undefined }]);+ expect(getSetting("aiToolkitUrl")).toBe("");+ const busy = await withFetch({ "http://10.0.0.7:8675/api/jobs": [200, jobs(2)] }, () => post({ provider: "ai-toolkit", value: "http://10.0.0.7:8675" }));+ expect(busy.result.body).toEqual({ ok: true, detail: "AI-Toolkit · 2 trainings running" });+ // AI_TOOLKIT_AUTH set on the trainer: it wants the token.+ const locked = await withFetch({ "http://10.0.0.7:8675/api/jobs": [401, { error: "Unauthorized" }] }, () => post({ provider: "ai-toolkit", value: "http://10.0.0.7:8675" }));+ expect(locked.result.body).toEqual({ ok: false, detail: "AI-Toolkit wants its auth token (AI_TOOLKIT_AUTH on the trainer): add it under Auth token" });+ const typed = await withFetch({ "http://10.0.0.7:8675/api/jobs": [401, { error: "Unauthorized" }] }, () =>+ post({ provider: "ai-toolkit", values: { aiToolkitUrl: "http://10.0.0.7:8675", aiToolkitToken: "wrong" } }),+ );+ expect(typed.result.body).toEqual({ ok: false, detail: "AI-Toolkit rejected the auth token (401)" });+ expect(typed.seen[0].auth).toBe("Bearer wrong");+ // Something else on that port, or nothing at all.+ const other = await withFetch({ "http://10.0.0.7:8675/api/jobs": [200, { hello: "world" }] }, () => post({ provider: "ai-toolkit", value: "http://10.0.0.7:8675" }));+ expect(other.result.body).toEqual({ ok: false, detail: "Something answers at http://10.0.0.7:8675, but it isn't AI-Toolkit's UI (port 8675 by default)" });+ const down = await withFetch({}, () => post({ provider: "ai-toolkit", value: "http://10.0.0.8:8675" }));+ expect(down.result.body).toMatchObject({ ok: false, detail: expect.stringMatching(/^Can't reach AI-Toolkit at http:\/\/10\.0\.0\.8:8675 .*Is its UI running\?/) });+ const none = await withFetch({}, () => post({ provider: "ai-toolkit" }));+ expect(none.result.body).toEqual({ ok: false, detail: "No AI-Toolkit URL set — its UI listens on http://127.0.0.1:8675" });+ });++ it("keeps the saved AI-Toolkit token with the trainer it was saved for", async () => {+ setSetting("aiToolkitUrl", "http://10.0.0.7:8675");+ setSetting("aiToolkitToken", "saved-aitk-token");+ const answers = { "http://10.0.0.7:8675/api/jobs": [200, { jobs: [] }], "http://10.0.0.9:8675/api/jobs": [401, { error: "Unauthorized" }] } as Record<string, [number, unknown]>;+ const saved = await withFetch(answers, () => post({ provider: "ai-toolkit" }));+ expect(saved.seen.map((r) => r.auth)).toEqual(["Bearer saved-aitk-token"]);+ // A new address gets no token unless one is typed with it, and says so when the trainer wants one.+ const other = await withFetch(answers, () => post({ provider: "ai-toolkit", value: "http://10.0.0.9:8675" }));+ expect(other.seen.map((r) => r.auth)).toEqual([undefined]);+ expect(other.result.body.detail).toBe("AI-Toolkit wants its auth token: type it with the new address (the saved one stays with http://10.0.0.7:8675)");+ const same = await withFetch(answers, () => post({ provider: "ai-toolkit", value: "http://10.0.0.7:8675/" }));+ expect(same.seen.map((r) => r.auth)).toEqual(["Bearer saved-aitk-token"]);+ setSetting("aiToolkitUrl", "");+ setSetting("aiToolkitToken", "");+ });++ it("checks the training photos folder can be written, without making it", async () => {+ const fresh = path.join(dir, "shared", "datasets");+ const ok = await post({ provider: "ai-toolkit", values: { aiToolkitDatasetDir: fresh }, field: "aiToolkitDatasetDir" });+ expect(ok.body).toEqual({ ok: true, detail: `Fuobe writes the training photos to ${fresh}: AI-Toolkit has to read the same folder` });+ expect(fs.existsSync(fresh)).toBe(false);+ const file = path.join(dir, "a-file");+ fs.writeFileSync(file, "");+ const blocked = await post({ provider: "ai-toolkit", values: { aiToolkitDatasetDir: path.join(file, "datasets") }, field: "aiToolkitDatasetDir" });+ expect(blocked.body).toMatchObject({ ok: false, detail: expect.stringMatching(/^Fuobe can't write to .*a-file/) });+ const relative = await post({ provider: "ai-toolkit", values: { aiToolkitDatasetDir: "datasets" }, field: "aiToolkitDatasetDir" });+ expect(relative.body.ok).toBe(false);+ expect(relative.body.detail).toMatch(/full path/);+ // Nothing typed and nothing saved: Fuobe's own data folder, for an AI-Toolkit on this machine.+ const own = await post({ provider: "ai-toolkit", field: "aiToolkitDatasetDir" });+ expect(own.body).toEqual({ ok: true, detail: `Fuobe writes the training photos to ${path.join(dir, "datasets")} (its data folder), for an AI-Toolkit on this machine` });+ });+it("refuses unknown providers and values a setting doesn't allow", async () => {expect((await post({ provider: "mock" })).status).toBe(400);expect((await post({ provider: "llm", values: { enhanceProvider: "gpt" } })).body).toMatchObject({ ok: false, detail: expect.stringMatching(/enhanceProvider must be one of/) });diff --git a/tests/settings-links.test.ts b/tests/settings-links.test.tsnew file mode 100644index 00000000..8b26eac4--- /dev/null+++ b/tests/settings-links.test.ts@@ -0,0 +1,27 @@+import fs from "node:fs";+import path from "node:path";+import { describe, expect, it } from "vitest";++/** Links into Settings (/settings#id) land on a section or field that exists. */++const root = path.join(__dirname, "../src");+const files = (d: string): string[] => fs.readdirSync(d, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? files(path.join(d, e.name)) : /\.tsx?$/.test(e.name) ? [path.join(d, e.name)] : []));+const form = fs.readFileSync(path.join(root, "components/settings-form.tsx"), "utf8");+/** The anchors Settings has: its sections' and fields' ids (id="…", or a Section's id prop on its own line). */+const anchors = new Set([...form.matchAll(/\bid="([a-z0-9-]+)"/g)].map((m) => m[1]));++describe("Settings deep links", () => {+ it("every /settings#… link in the app has its anchor", () => {+ const links = files(root).flatMap((f) => [...fs.readFileSync(f, "utf8").matchAll(/\/settings#([a-z0-9-]+)/g)].map((m) => ({ file: path.relative(root, f), id: m[1] })));+ expect(links.length).toBeGreaterThan(5);+ for (const l of links) expect(anchors.has(l.id), `${l.file} links to /settings#${l.id}`).toBe(true);+ });++ it("the AI-Toolkit URL the training messages ask for has its field, with Save & test", () => {+ const section = form.slice(form.indexOf('id="training"'), form.indexOf("</Section>", form.indexOf('id="training"')));+ expect(section).toMatch(/name="aiToolkitUrl"[\s\S]*provider="ai-toolkit"/);+ expect(section).toMatch(/name="aiToolkitToken"/);+ const training = fs.readFileSync(path.join(root, "server/training.ts"), "utf8");+ expect(training).toContain("Settings → Training");+ });+});