diff --git a/CLAUDE.md b/CLAUDE.md index d3cf4fe..4f4a5eb 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -200,7 +200,29 @@ Vorlagen ersetzt. `tests/seed.test.ts` prüft die Dateien. Ein Haushalt Hinweis darüber. Das Bild der Seite wird erst beim Speichern geholt und wie ein eigenes Foto verkleinert. `IMPORT_TEST_ORIGIN` erlaubt genau eine lokale Quelle für den Browser-Test — nie im Chart setzen. -- 4c (KI-Einstellung, Kochbuchfoto) folgt. +- Kochbuchfoto (4c): `/gerichte/foto` → `POST /api/dishes/photo-import`. Das + Bildmodell schreibt Titel, Zutatenzeilen (wörtlich) und Schritte ab; Zuordnung + und Umrechnung macht die App selbst (`lib/recipe-draft.ts`, derselbe Weg wie + beim Link). Das Foto wird nicht gespeichert. Seiten ohne JSON-LD liest das + Textmodell, wenn eines eingerichtet ist. Ein AI-Entwurf trägt den Hinweis + „Von der AI gelesen“. + +## AI + +- Einstellung je Haushalt in `household_ai` (`/mehr/ki`, nur Admin): Adresse eines + OpenAI-kompatiblen Endpunkts (LiteLLM auf der Box), Bild- und Textmodell, + Schlüssel. **Kein Vorgabewert** — jede geratene Adresse ist auf einer anderen + Box falsch. Zugriff nur über `lib/ai.ts`. +- **Kein stilles Ausweichen in die Cloud.** Ist nichts eingerichtet, sagt die + Oberfläche das; ist der Dienst weg, sagt sie das auch. +- **Vorschläge füllen die Maske, speichern tut ein Mensch.** Mengen kommen nie + aus dem Modell gerechnet: Es schreibt die Zeile ab, `lib/recipe-import.ts` + liest Zahl und Einheit. +- Ein nachdenkendes Modell braucht Platz (`max_tokens` 6000); `` und + Code-Zäune fallen beim Lesen weg (`parseJsonReply`). +- Der Schlüssel liegt verschlüsselt (`lib/vault.ts`, AES-256-GCM, `tresor.key` + unter `/app/data`). **Abzug und `tresor.key` gehören zusammen** — wer nur die + Sicherung hat, hat den Schlüssel nicht. ## Lokal entwickeln diff --git a/OlaresManifest.yaml b/OlaresManifest.yaml index 48b9289..da61aa7 100644 --- a/OlaresManifest.yaml +++ b/OlaresManifest.yaml @@ -21,7 +21,7 @@ metadata: title: What's cooking? description: The family decides together what's for dinner — and the shopping list writes itself. Runs entirely on your own box. icon: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png - version: 26.11.6 + version: 26.11.7 categories: - Applications @@ -61,7 +61,7 @@ permission: appData: true spec: - versionName: '26.11.6' + versionName: '26.11.7' featuredImage: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png promoteImage: diff --git a/app/(app)/gerichte/foto/page.tsx b/app/(app)/gerichte/foto/page.tsx new file mode 100644 index 0000000..67b861a --- /dev/null +++ b/app/(app)/gerichte/foto/page.tsx @@ -0,0 +1,40 @@ +import { Settings } from "lucide-react"; +import Link from "next/link"; +import { redirect } from "next/navigation"; +import { getTranslations } from "next-intl/server"; +import { PhotoImport } from "@/components/dishes/photo-import"; +import { loadAi } from "@/lib/ai"; +import { requireSession } from "@/lib/auth/session"; +import { withHousehold } from "@/lib/db"; + +export const dynamic = "force-dynamic"; + +export default async function PhotoDishPage() { + const session = await requireSession(); + if (session.role !== "admin" && session.role !== "member") redirect("/gerichte"); + const t = await getTranslations("dishes"); + const ai = await withHousehold(session.householdId, loadAi); + return ( +
+
+

{t("addEyebrow")}

+

{t("photo.title")}

+
+ {ai?.visionModel ? ( + + ) : ( +
+

{t("photo.notConfigured")}

+ {session.role === "admin" ? ( + + + {t("photo.setUp")} + + ) : ( +

{t("photo.askAdmin")}

+ )} +
+ )} +
+ ); +} diff --git a/app/(app)/gerichte/hinzufuegen/page.tsx b/app/(app)/gerichte/hinzufuegen/page.tsx index 028549c..31188ec 100644 --- a/app/(app)/gerichte/hinzufuegen/page.tsx +++ b/app/(app)/gerichte/hinzufuegen/page.tsx @@ -3,18 +3,16 @@ import Link from "next/link"; import { getTranslations } from "next-intl/server"; import { requireSession } from "@/lib/auth/session"; -// Wege in den Pool. Das Foto aus dem Kochbuch folgt mit Arbeitspaket 4c. +// Wege in den Pool: Klassiker, Link, Kochbuchfoto, von Hand. export default async function AddDishPage() { await requireSession(); const t = await getTranslations("dishes"); const options = [ { href: "/gerichte/vorlagen", icon: Sparkles, title: t("addStarters"), text: t("addStartersText") }, { href: "/gerichte/link", icon: Link2, title: t("addLink"), text: t("addLinkText") }, + { href: "/gerichte/foto", icon: Camera, title: t("addPhoto"), text: t("addPhotoText") }, { href: "/gerichte/neu", icon: PenLine, title: t("addManual"), text: t("addManualText") }, ]; - const soon = [ - { icon: Camera, title: t("addPhoto") }, - ]; return (
@@ -34,13 +32,6 @@ export default async function AddDishPage() { ))} - {soon.map(({ icon: Icon, title }) => ( -
  • - - {title} - {t("soon")} -
  • - ))}
    ); diff --git a/app/(app)/mehr/ki/page.tsx b/app/(app)/mehr/ki/page.tsx new file mode 100644 index 0000000..fd50bcb --- /dev/null +++ b/app/(app)/mehr/ki/page.tsx @@ -0,0 +1,27 @@ +import { redirect } from "next/navigation"; +import { getTranslations } from "next-intl/server"; +import { AiSettings } from "@/components/more/ai-settings"; +import { loadAi } from "@/lib/ai"; +import { requireSession } from "@/lib/auth/session"; +import { withHousehold } from "@/lib/db"; + +export const dynamic = "force-dynamic"; + +export default async function AiSettingsPage() { + const session = await requireSession(); + if (session.role !== "admin") redirect("/mehr"); + const t = await getTranslations("more.ai"); + const ai = await withHousehold(session.householdId, loadAi); + return ( +
    +
    +

    {session.householdName}

    +

    {t("title")}

    +

    {t("intro")}

    +
    + +
    + ); +} diff --git a/app/(app)/mehr/page.tsx b/app/(app)/mehr/page.tsx index 05102c8..ad899b3 100644 --- a/app/(app)/mehr/page.tsx +++ b/app/(app)/mehr/page.tsx @@ -1,3 +1,5 @@ +import { ChevronRight } from "lucide-react"; +import Link from "next/link"; import { getLocale, getTranslations } from "next-intl/server"; import { AddDevice, InvitePerson } from "@/components/more/invite-panel"; import { LanguageSelect, SignOutButton } from "@/components/more/account-actions"; @@ -20,7 +22,7 @@ export default async function MorePage() { const session = await requireSession(); const t = await getTranslations("more"); const locale = await getLocale(); - const { members, passkeys, founder } = await withHousehold(session.householdId, async (client) => { + const { members, passkeys, founder, aiReady } = await withHousehold(session.householdId, async (client) => { const members = (await client.query("select id, display_name, role from members order by created_at")).rows; const founder = (await client.query("select created_by from households")).rows[0]?.created_by as string | null; const passkeys = ( @@ -28,7 +30,8 @@ export default async function MorePage() { session.memberId, ]) ).rows; - return { members, passkeys, founder }; + const aiReady = (await client.query("select 1 from household_ai")).rowCount! > 0; + return { members, passkeys, founder, aiReady }; }); const date = new Intl.DateTimeFormat(locale, { dateStyle: "medium" }); @@ -83,6 +86,21 @@ export default async function MorePage() { + {session.role === "admin" ? ( +
    + + + {aiReady ? t("ai.ready") : t("ai.notReady")} + {t("ai.summary")} + + + +
    + ) : null} +
    diff --git a/app/api/ai/settings/route.ts b/app/api/ai/settings/route.ts new file mode 100644 index 0000000..1c7b27d --- /dev/null +++ b/app/api/ai/settings/route.ts @@ -0,0 +1,48 @@ +import { z } from "zod"; +import { guardWrite, isResponse } from "@/lib/auth/guard"; +import { fail, json, readJson } from "@/lib/auth/http"; +import { withHousehold } from "@/lib/db"; +import { seal } from "@/lib/vault"; + +export const dynamic = "force-dynamic"; + +// AI-Einstellung des Haushalts, nur für Admins. Der Schlüssel geht nur hinein: +// gespeichert verschlüsselt (lib/vault.ts), nie zurückgegeben. +const input = z.object({ + endpoint: z + .string() + .trim() + .url() + .max(500) + .refine((u) => /^https?:\/\//.test(u)), + textModel: z.string().trim().max(200).nullable().optional(), + visionModel: z.string().trim().max(200).nullable().optional(), + // undefined: Schlüssel bleibt; Text: neuer Schlüssel; null: Schlüssel entfernen + apiKey: z.string().trim().max(500).nullable().optional(), +}); + +export async function PUT(request: Request) { + const session = await guardWrite(request, ["admin"]); + if (isResponse(session)) return session; + const body = input.safeParse(await readJson(request)); + if (!body.success) return fail("invalid", 400); + const { endpoint, textModel, visionModel, apiKey } = body.data; + const sealed = apiKey ? await seal(apiKey) : null; + await withHousehold(session.householdId, (c) => + c.query( + `insert into household_ai (household_id, endpoint, text_model, vision_model, api_key_enc, updated_by) + values ($1, $2, $3, $4, $5, $6) + on conflict (household_id) do update set endpoint = $2, text_model = $3, vision_model = $4, + api_key_enc = case when $7 then $5 else household_ai.api_key_enc end, updated_by = $6, updated_at = now()`, + [session.householdId, endpoint, textModel || null, visionModel || null, sealed, session.memberId, apiKey !== undefined], + ), + ); + return json({ ok: true }); +} + +export async function DELETE(request: Request) { + const session = await guardWrite(request, ["admin"]); + if (isResponse(session)) return session; + await withHousehold(session.householdId, (c) => c.query("delete from household_ai")); + return json({ ok: true }); +} diff --git a/app/api/ai/test/route.ts b/app/api/ai/test/route.ts new file mode 100644 index 0000000..2c81d67 --- /dev/null +++ b/app/api/ai/test/route.ts @@ -0,0 +1,15 @@ +import { checkConnection, loadAi } from "@/lib/ai"; +import { guardWrite, isResponse } from "@/lib/auth/guard"; +import { fail, json } from "@/lib/auth/http"; +import { withHousehold } from "@/lib/db"; + +export const dynamic = "force-dynamic"; + +// „Verbindung prüfen“ mit der gespeicherten Einstellung. +export async function POST(request: Request) { + const session = await guardWrite(request, ["admin"]); + if (isResponse(session)) return session; + const ai = await withHousehold(session.householdId, loadAi); + if (!ai) return fail("aiNotConfigured", 409); + return json(await checkConnection(ai)); +} diff --git a/app/api/dishes/import/route.ts b/app/api/dishes/import/route.ts index 0925e2c..7cc1bb6 100644 --- a/app/api/dishes/import/route.ts +++ b/app/api/dishes/import/route.ts @@ -1,17 +1,18 @@ import { getLocale } from "next-intl/server"; import { z } from "zod"; +import { AiUnavailable, askJson, loadAi, RECIPE_PROMPT, recipeFromReply } from "@/lib/ai"; import { guardWrite, isResponse } from "@/lib/auth/guard"; import { fail, json, readJson } from "@/lib/auth/http"; +import { withHousehold } from "@/lib/db"; import { FetchRefused, fetchPublic } from "@/lib/fetch-safe"; -import { allIngredients } from "@/lib/ingredients"; -import { INPUT_UNITS } from "@/lib/dishes"; -import { extractRecipe, matchLines } from "@/lib/recipe-import"; -import { toBase } from "@/lib/units"; +import { draftFromRecipe, pageText } from "@/lib/recipe-draft"; +import { extractRecipe } from "@/lib/recipe-import"; export const dynamic = "force-dynamic"; // Rezept-Link → Entwurf. Gespeichert wird nichts: Die Person sieht den -// Entwurf im Formular, prüft die Mengen und speichert selbst. +// Entwurf im Formular, prüft die Mengen und speichert selbst. Ohne JSON-LD +// fragt die App das Textmodell — nur, wenn der Haushalt eines eingerichtet hat. export async function POST(request: Request) { const session = await guardWrite(request); if (isResponse(session)) return session; @@ -24,26 +25,22 @@ export async function POST(request: Request) { if (error instanceof FetchRefused) return fail(error.message === "url" || error.message === "host" || error.message === "port" ? "url" : "unreachable", 422); throw error; } - const recipe = extractRecipe(page.body.toString("utf8")); - if (!recipe || !recipe.title) return fail("noRecipe", 422); - const locale = await getLocale(); - const lines = matchLines(recipe.ingredients, await allIngredients(), locale); - return json({ - title: recipe.title, - portions: recipe.yield ?? 4, - effortMinutes: recipe.totalMinutes, - sourceUrl: page.url, - imageUrl: recipe.image ? new URL(recipe.image, page.url).toString() : null, - ingredients: lines - .filter((l) => l.ingredient) - .map((l) => { - // Maße, die das Formular nicht anbietet (cl, Tasse), gleich in die Basiseinheit. - if (l.qty !== null && l.unit && !(INPUT_UNITS as readonly string[]).includes(l.unit)) { - return { ingredient: l.ingredient, qty: toBase(l.qty, l.unit, l.ingredient!.unit), unit: l.ingredient!.unit, note: l.note }; - } - return { ingredient: l.ingredient, qty: l.qty, unit: l.unit, note: l.note }; - }), - unmatched: lines.filter((l) => !l.ingredient).map((l) => l.raw), - steps: recipe.steps.map((text) => ({ text, timerMinutes: null })), - }); + const html = page.body.toString("utf8"); + let recipe = extractRecipe(html); + let byAi = false; + if (!recipe || !recipe.title) { + const ai = await withHousehold(session.householdId, loadAi); + const text = pageText(html); + if (!ai?.textModel || text.length < 80) return fail("noRecipe", 422); + try { + recipe = recipeFromReply(await askJson(ai, "text", RECIPE_PROMPT, text)); + } catch (error) { + if (error instanceof AiUnavailable) return fail("aiUnavailable", 503); + throw error; + } + if (!recipe) return fail("noRecipe", 422); + byAi = true; + } + const imageUrl = recipe.image ? new URL(recipe.image, page.url).toString() : null; + return json({ ...(await draftFromRecipe(recipe, await getLocale(), { sourceUrl: page.url, imageUrl })), byAi }); } diff --git a/app/api/dishes/photo-import/route.ts b/app/api/dishes/photo-import/route.ts new file mode 100644 index 0000000..90ff29b --- /dev/null +++ b/app/api/dishes/photo-import/route.ts @@ -0,0 +1,44 @@ +import { getLocale } from "next-intl/server"; +import { AiNotConfigured, AiUnavailable, askJson, loadAi, RECIPE_PROMPT, recipeFromReply } from "@/lib/ai"; +import { guardWrite, isResponse } from "@/lib/auth/guard"; +import { fail, json } from "@/lib/auth/http"; +import { withHousehold } from "@/lib/db"; +import { imageForModel, PhotoRejected } from "@/lib/photos"; +import { draftFromRecipe } from "@/lib/recipe-draft"; + +export const dynamic = "force-dynamic"; + +// Kochbuchfoto → Entwurf. Das Bildmodell schreibt die Zutatenzeilen wörtlich +// ab; Zuordnung und Umrechnung macht die App selbst (lib/recipe-import.ts). +// Das Foto wird nicht gespeichert. +export async function POST(request: Request) { + const session = await guardWrite(request); + if (isResponse(session)) return session; + const ai = await withHousehold(session.householdId, loadAi); + if (!ai?.visionModel) return fail("aiNotConfigured", 409); + const form = await request.formData().catch(() => null); + const files = (form?.getAll("photos") ?? []).filter((f): f is File => f instanceof File).slice(0, 2); + if (!files.length) return fail("photo", 400); + let images: string[]; + try { + images = await Promise.all(files.map(imageForModel)); + } catch (error) { + if (error instanceof PhotoRejected) return fail("photo", 400); + throw error; + } + let recipe; + try { + recipe = recipeFromReply( + await askJson(ai, "vision", RECIPE_PROMPT, [ + { type: "text", text: "Read the recipe on these cookbook pages." }, + ...images.map((url) => ({ type: "image_url" as const, image_url: { url } })), + ]), + ); + } catch (error) { + if (error instanceof AiNotConfigured) return fail("aiNotConfigured", 409); + if (error instanceof AiUnavailable) return fail("aiUnavailable", 503); + throw error; + } + if (!recipe) return fail("noRecipe", 422); + return json({ ...(await draftFromRecipe(recipe, await getLocale())), byAi: true }); +} diff --git a/components/dishes/dish-form.tsx b/components/dishes/dish-form.tsx index 8a85581..8e83ab1 100644 --- a/components/dishes/dish-form.tsx +++ b/components/dishes/dish-form.tsx @@ -1,6 +1,6 @@ "use client"; -import { ArrowDown, ArrowUp, Plus, X } from "lucide-react"; +import { ArrowDown, ArrowUp, Plus, Sparkles, X } from "lucide-react"; import { useRouter } from "next/navigation"; import { useTranslations } from "next-intl"; import { useEffect, useId, useRef, useState } from "react"; @@ -31,6 +31,8 @@ export type DishFormValue = { imageUrl?: string | null; /** Zeilen einer Rezeptseite, die keiner Zutat zugeordnet werden konnten. */ unmatched?: string[]; + /** Von der AI gelesen (Kochbuchfoto, Seite ohne JSON-LD): als solches erkennbar. */ + byAi?: boolean; }; const UNITS_FOR: Record = { @@ -131,6 +133,12 @@ export function DishForm({ initial }: { initial?: DishFormValue }) { return (
    + {initial?.byAi ? ( +

    + + {t("form.byAi")} +

    + ) : null}
    diff --git a/components/dishes/link-import.tsx b/components/dishes/link-import.tsx index 705c98b..afd48d1 100644 --- a/components/dishes/link-import.tsx +++ b/components/dishes/link-import.tsx @@ -29,7 +29,7 @@ export function LinkImport() { const data = await res.json().catch(() => ({})); setBusy(false); if (!res.ok) { - setError(["url", "unreachable", "noRecipe"].includes(data.error) ? data.error : "unknown"); + setError(["url", "unreachable", "noRecipe", "aiUnavailable"].includes(data.error) ? data.error : "unknown"); return; } setDraft({ ...data, base: null, tags: [], isTrial: true }); diff --git a/components/dishes/photo-import.tsx b/components/dishes/photo-import.tsx new file mode 100644 index 0000000..db28aeb --- /dev/null +++ b/components/dishes/photo-import.tsx @@ -0,0 +1,60 @@ +"use client"; + +import { Camera } from "lucide-react"; +import { useTranslations } from "next-intl"; +import { useState } from "react"; +import { Button } from "@/components/ui/button"; +import { ErrorNotice } from "@/components/ui/notice"; +import { DishForm, type DishFormValue } from "./dish-form"; + +// Kochbuchfoto → Entwurf. Das Bildmodell liest die Seite (app/api/dishes/photo-import), +// die Person prüft und speichert. Das Foto selbst wird nicht aufbewahrt. +export function PhotoImport() { + const t = useTranslations("dishes.photo"); + const [files, setFiles] = useState([]); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const [draft, setDraft] = useState(null); + + async function read(event: React.FormEvent) { + event.preventDefault(); + if (!files.length) return; + setBusy(true); + setError(null); + const body = new FormData(); + for (const f of files) body.append("photos", f); + const res = await fetch("/api/dishes/photo-import", { method: "POST", body }); + const data = await res.json().catch(() => ({})); + setBusy(false); + if (!res.ok) { + setError(["photo", "noRecipe", "aiUnavailable", "aiNotConfigured"].includes(data.error) ? data.error : "unknown"); + return; + } + setDraft({ ...data, base: null, tags: [], isTrial: true }); + } + + if (draft) return ; + return ( + + + {error ? {t(`errors.${error}`)} : null} + + {busy ?

    {t("readingHint")}

    : null} + + ); +} diff --git a/components/more/ai-settings.tsx b/components/more/ai-settings.tsx new file mode 100644 index 0000000..1653e6a --- /dev/null +++ b/components/more/ai-settings.tsx @@ -0,0 +1,156 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { useTranslations } from "next-intl"; +import { useState } from "react"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { ErrorNotice } from "@/components/ui/notice"; + +type Current = { endpoint: string; textModel: string | null; visionModel: string | null; hasKey: boolean } | null; +type Check = + | { ok: true; models: string[]; textFound: boolean | null; visionFound: boolean | null } + | { ok: false; reason: "unreachable" | "key" | "status" | "aiNotConfigured" }; + +// AI-Einstellung (nur Admin). Keine vorgegebene Adresse: Die Box kennt ihre eigene. +export function AiSettings({ current }: { current: Current }) { + const t = useTranslations("more.ai"); + const router = useRouter(); + const [endpoint, setEndpoint] = useState(current?.endpoint ?? ""); + const [textModel, setTextModel] = useState(current?.textModel ?? ""); + const [visionModel, setVisionModel] = useState(current?.visionModel ?? ""); + const [apiKey, setApiKey] = useState(""); + const [removeKey, setRemoveKey] = useState(false); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const [saved, setSaved] = useState(false); + const [check, setCheck] = useState(null); + + async function save(event: React.FormEvent) { + event.preventDefault(); + setBusy(true); + setError(null); + setSaved(false); + setCheck(null); + const res = await fetch("/api/ai/settings", { + method: "PUT", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + endpoint: endpoint.trim(), + textModel: textModel.trim() || null, + visionModel: visionModel.trim() || null, + ...(removeKey ? { apiKey: null } : apiKey.trim() ? { apiKey: apiKey.trim() } : {}), + }), + }); + setBusy(false); + if (!res.ok) { + setError("invalid"); + return; + } + setApiKey(""); + setRemoveKey(false); + setSaved(true); + router.refresh(); + } + + async function test() { + setBusy(true); + setCheck(null); + setSaved(false); + const res = await fetch("/api/ai/test", { method: "POST" }); + const data = await res.json().catch(() => ({})); + setBusy(false); + setCheck(res.ok ? data : { ok: false, reason: data.error === "aiNotConfigured" ? "aiNotConfigured" : "status" }); + } + + async function removeAll() { + setBusy(true); + await fetch("/api/ai/settings", { method: "DELETE" }); + setBusy(false); + setEndpoint(""); + setTextModel(""); + setVisionModel(""); + setCheck(null); + setSaved(false); + router.refresh(); + } + + return ( +
    +
    + + setEndpoint(e.target.value)} /> +

    {t("endpointHint")}

    +
    +
    + + setVisionModel(e.target.value)} /> +

    {t("visionHint")}

    +
    +
    + + setTextModel(e.target.value)} /> +

    {t("textHint")}

    +
    +
    + + setApiKey(e.target.value)} + /> + {current?.hasKey ? ( + + ) : null} +
    + {error ? {t("errors.invalid")} : null} + {saved ? ( +

    + {t("saved")} +

    + ) : null} + {check ? : null} +
    + + {current ? ( + + ) : null} +
    + {current ? ( + + ) : null} + + ); +} + +function CheckResult({ check }: { check: Check }) { + const t = useTranslations("more.ai.check"); + if (!check.ok) return {t(check.reason)}; + const missing = [check.visionFound === false ? "vision" : null, check.textFound === false ? "text" : null].filter(Boolean) as string[]; + if (missing.length) { + return ( + + {t("modelMissing", { models: check.models.slice(0, 8).join(", ") || "–" })} + + ); + } + return ( +

    + {t("ok")} +

    + ); +} diff --git a/db/migrations/0005_ai_settings.sql b/db/migrations/0005_ai_settings.sql new file mode 100644 index 0000000..739887b --- /dev/null +++ b/db/migrations/0005_ai_settings.sql @@ -0,0 +1,20 @@ +-- AI-Einstellung je Haushalt (Arbeitspaket 4c): Adresse eines OpenAI-kompatiblen +-- Endpunkts (LiteLLM auf der Box), Modellnamen für Text und Bild, Schlüssel +-- verschlüsselt (lib/vault.ts, tresor.key unter /app/data). Kein Vorgabewert: +-- Jede geratene Adresse ist auf einer anderen Box falsch. + +create table household_ai ( + household_id uuid primary key references households (id) on delete cascade, + endpoint text not null check (endpoint ~ '^https?://' and length(endpoint) <= 500), + text_model text check (length(text_model) between 1 and 200), + vision_model text check (length(vision_model) between 1 and 200), + api_key_enc bytea, + updated_by uuid, + updated_at timestamptz not null default now(), + foreign key (updated_by, household_id) references members (id, household_id) on delete set null (updated_by) +); + +alter table household_ai enable row level security; +alter table household_ai force row level security; +create policy household_ai_household on household_ai + using (household_id = app_household_id()) with check (household_id = app_household_id()); diff --git a/docs/PROJEKTSTART.md b/docs/PROJEKTSTART.md index d103343..f0afbb9 100644 --- a/docs/PROJEKTSTART.md +++ b/docs/PROJEKTSTART.md @@ -51,7 +51,7 @@ Das Repo erbt sie, weil es in der Organisation liegt. 3. **Seed:** etwa 300 kanonische Zutaten in vier Sprachen, Starter-Pool DE und EN, Gangfolgen REWE, Edeka, Lidl, Aldi. **Erledigt** in 26.11.5 (340 Zutaten, je 15 Starter, fünf Gangfolgen; Einspielen bei jedem Start). 4. **Gerichte:** von Hand, Import per JSON-LD, Foto-Import über LiteLLM. - **4a und 4b erledigt** in 26.11.6 (Pool, Klassiker, Ansicht mit Portionen, Anlegen/Bearbeiten, Fotos, Rezept-Link über JSON-LD); 4c KI folgt. + **Erledigt:** 4a und 4b in 26.11.6 (Pool, Klassiker, Portionen, Anlegen/Bearbeiten, Fotos, Rezept-Link über JSON-LD); 4c in 26.11.7 (AI-Einstellung mit Tresor, Kochbuchfoto über das Bildmodell, Textmodell für Seiten ohne JSON-LD). 5. **Wünschen:** Jetons, Kacheln, Kinder-Login mit Haushaltscode und PIN. 6. **Runde und Slots:** `lib/suggest.ts` mit Tests, Drag and Drop, Freigabe. 7. **Einkaufsliste:** `lib/aggregate.ts` mit Tests, Gangsortierung, Echtzeit (SSE), Offline-Warteschlange. diff --git a/e2e/gerichte.spec.ts b/e2e/gerichte.spec.ts index c684926..1674ea7 100644 --- a/e2e/gerichte.spec.ts +++ b/e2e/gerichte.spec.ts @@ -159,3 +159,94 @@ test.describe("recipe link", () => { await expect(page.locator(`main a[href="${origin}/rezept"]`)).toBeVisible(); }); }); + +// Kochbuchfoto und Textmodell: ein kleiner Server in OpenAI-Form spielt LiteLLM +// (gleiche Testadresse wie oben). Er antwortet mit festen Rezepten und prüft +// den Schlüssel — so sieht der Test auch, dass der Tresor ihn richtig herausgibt. +test.describe("cookbook photo and AI setting", () => { + let server: import("node:http").Server; + const origin = process.env.IMPORT_TEST_ORIGIN ?? "http://127.0.0.1:3021"; + const reply = (r: object) => JSON.stringify({ choices: [{ message: { content: "```json\n" + JSON.stringify(r) + "\n```" } }] }); + + test.beforeAll(async () => { + const { createServer } = await import("node:http"); + server = createServer((req, res) => { + let raw = ""; + req.on("data", (c) => (raw += c)); + req.on("end", () => { + if (req.url === "/blog") { + const text = "Unsere liebste Pasta. ".repeat(10) + "Zutaten: 400 g Spaghetti, Salz. Nudeln kochen."; + return res.writeHead(200, { "content-type": "text/html" }).end(`

    ${text}

    `); + } + if (!req.url?.startsWith("/v1/")) return res.writeHead(404).end(); + if (req.headers.authorization !== "Bearer sk-test") return res.writeHead(401).end(); + if (req.url === "/v1/models") { + return res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ data: [{ id: "qwen-vl" }, { id: "qwen-text" }] })); + } + const withImage = raw.includes("image_url"); + res.writeHead(200, { "content-type": "application/json" }).end( + withImage + ? reply({ title: "Kartoffelsalat aus dem Kochbuch", portions: 4, minutes: 40, ingredients: ["1 kg Kartoffeln", "2 Zwiebeln", "1 Glas Gurken"], steps: ["Kartoffeln kochen.", "Alles mischen."] }) + : reply({ title: "Blog-Pasta", portions: 2, minutes: 15, ingredients: ["400 g Spaghetti", "Salz"], steps: ["Nudeln kochen."] }), + ); + }); + }); + await new Promise((done) => server.listen(Number(new URL(origin).port), "127.0.0.1", done)); + }); + test.afterAll(() => new Promise((done) => server.close(() => done()))); + + async function fillMissingAmounts(page: import("@playwright/test").Page) { + const amounts = page.getByRole("textbox", { name: "Menge", exact: true }); + for (let i = 0; i < (await amounts.count()); i++) { + if (!(await amounts.nth(i).inputValue())) await amounts.nth(i).fill("1"); + } + } + + test("without an image model the photo page says how to set it up", async ({ page }) => { + await page.goto("/gerichte/hinzufuegen"); + await page.getByRole("link", { name: /Kochbuch fotografieren/ }).click(); + await expect(page.getByText("braucht Lunch ein Bildmodell")).toBeVisible(); + await page.getByRole("link", { name: "AI einrichten" }).click(); + await expect(page).toHaveURL(/\/mehr\/ki$/); + }); + + test("an admin sets up the AI and checks the connection", async ({ page }) => { + await page.goto("/mehr/ki"); + await page.fill("#ai-endpoint", `${origin}/v1`); + await page.fill("#ai-vision", "qwen-vl"); + await page.fill("#ai-text", "qwen-text"); + await page.fill("#ai-key", "sk-wrong"); + await page.getByRole("button", { name: "Speichern" }).click(); + await expect(page.getByRole("status")).toHaveText("Gespeichert."); + await page.getByRole("button", { name: "Verbindung prüfen" }).click(); + await expect(page.locator("main [role=alert]")).toContainText("Schlüssel wurde abgelehnt"); + await page.fill("#ai-key", "sk-test"); + await page.getByRole("button", { name: "Speichern" }).click(); + await expect(page.getByRole("status")).toHaveText("Gespeichert."); + await expect(page.locator("#ai-key")).toHaveAttribute("placeholder", /Hinterlegt/); + await page.getByRole("button", { name: "Verbindung prüfen" }).click(); + await expect(page.getByRole("status")).toContainText("Verbunden"); + await page.goto("/mehr"); + await expect(page.getByRole("link", { name: /Eingerichtet/ })).toBeVisible(); + }); + + test("a cookbook photo becomes a draft marked as read by the AI", async ({ page }) => { + await page.goto("/gerichte/foto"); + const jpg = await sharp({ create: { width: 1000, height: 1400, channels: 3, background: { r: 245, g: 240, b: 230 } } }).jpeg().toBuffer(); + await page.locator("input[type=file]").setInputFiles({ name: "seite.jpg", mimeType: "image/jpeg", buffer: jpg }); + await page.getByRole("button", { name: "Rezept lesen" }).click(); + await expect(page.locator("#title")).toHaveValue("Kartoffelsalat aus dem Kochbuch"); + await expect(page.getByRole("note").first()).toContainText("Von der AI gelesen"); + await fillMissingAmounts(page); + await page.getByRole("button", { name: "Speichern" }).click(); + await expect(page.getByRole("heading", { level: 1 })).toHaveText("Kartoffelsalat aus dem Kochbuch"); + }); + + test("a page without recipe data is read by the text model", async ({ page }) => { + await page.goto("/gerichte/link"); + await page.fill("#recipe-url", `${origin}/blog`); + await page.getByRole("button", { name: "Rezept holen" }).click(); + await expect(page.locator("#title")).toHaveValue("Blog-Pasta"); + await expect(page.getByRole("note").first()).toContainText("Von der AI gelesen"); + }); +}); diff --git a/e2e/rundgang.spec.ts b/e2e/rundgang.spec.ts index e7160bb..e52864b 100644 --- a/e2e/rundgang.spec.ts +++ b/e2e/rundgang.spec.ts @@ -16,6 +16,8 @@ const SIGNED_IN = [ { path: "/gerichte/vorlagen", heading: "Gerichte übernehmen" }, { path: "/gerichte/neu", heading: "Neues Gericht" }, { path: "/gerichte/link", heading: "Rezept-Link einfügen" }, + { path: "/gerichte/foto", heading: "Kochbuch fotografieren" }, + { path: "/mehr/ki", heading: "AI" }, ]; const SIGNED_OUT = [ { path: "/anmelden", heading: "Anmelden" }, diff --git a/lib/ai.ts b/lib/ai.ts new file mode 100644 index 0000000..31799bd --- /dev/null +++ b/lib/ai.ts @@ -0,0 +1,135 @@ +import "server-only"; +import type pg from "pg"; +import { z } from "zod"; +import type { RawRecipe } from "./recipe-import"; +import { unseal } from "./vault"; + +// AI über einen OpenAI-kompatiblen Endpunkt (LiteLLM auf der Box, Konzept +// „Technik“). Regeln (CLAUDE.md, „AI“): kein Vorgabe-Endpunkt, die App kennt +// nur Modellnamen, kein stilles Ausweichen in die Cloud, das Ergebnis ist ein +// Entwurf, den ein Mensch prüft und speichert. + +export type AiSettings = { + endpoint: string; + textModel: string | null; + visionModel: string | null; + apiKeyEnc: Buffer | null; +}; + +export class AiNotConfigured extends Error {} +export class AiUnavailable extends Error {} + +export async function loadAi(client: pg.PoolClient | pg.Client): Promise { + const row = ( + await client.query( + `select endpoint, text_model as "textModel", vision_model as "visionModel", api_key_enc as "apiKeyEnc" from household_ai`, + ) + ).rows[0]; + return row ?? null; +} + +const base = (endpoint: string) => endpoint.replace(/\/+$/, ""); + +async function headers(settings: AiSettings): Promise> { + const h: Record = { "content-type": "application/json" }; + if (settings.apiKeyEnc) h.authorization = `Bearer ${await unseal(settings.apiKeyEnc)}`; + return h; +} + +export type ConnectionCheck = + | { ok: true; models: string[]; textFound: boolean | null; visionFound: boolean | null } + | { ok: false; reason: "unreachable" | "key" | "status" }; + +/** „Verbindung prüfen“: GET /models — erreichbar, Schlüssel angenommen, Modelle vorhanden? */ +export async function checkConnection(settings: AiSettings): Promise { + let res: Response; + try { + res = await fetch(`${base(settings.endpoint)}/models`, { headers: await headers(settings), signal: AbortSignal.timeout(10_000) }); + } catch { + return { ok: false, reason: "unreachable" }; + } + if (res.status === 401 || res.status === 403) return { ok: false, reason: "key" }; + if (!res.ok) return { ok: false, reason: "status" }; + const data = (await res.json().catch(() => ({}))) as { data?: { id?: string }[] }; + const models = (data.data ?? []).map((m) => m.id ?? "").filter(Boolean); + const has = (m: string | null) => (m ? models.includes(m) : null); + return { ok: true, models, textFound: has(settings.textModel), visionFound: has(settings.visionModel) }; +} + +type Content = string | ({ type: "text"; text: string } | { type: "image_url"; image_url: { url: string } })[]; + +/** Modellantwort → JSON-Objekt. Nachdenk-Blöcke und Code-Zäune fallen weg. */ +export function parseJsonReply(text: string): unknown { + const cleaned = text.replace(/[\s\S]*?<\/think>/g, "").replace(/```(?:json)?/g, ""); + const start = cleaned.indexOf("{"); + const end = cleaned.lastIndexOf("}"); + if (start < 0 || end <= start) return null; + try { + return JSON.parse(cleaned.slice(start, end + 1)); + } catch { + return null; + } +} + +/** Eine Frage an das Text- oder Bildmodell; die Antwort muss JSON sein. */ +export async function askJson(settings: AiSettings, kind: "text" | "vision", system: string, user: Content): Promise { + const model = kind === "vision" ? settings.visionModel : settings.textModel; + if (!model) throw new AiNotConfigured(kind); + let res: Response; + try { + res = await fetch(`${base(settings.endpoint)}/chat/completions`, { + method: "POST", + headers: await headers(settings), + signal: AbortSignal.timeout(120_000), + body: JSON.stringify({ + model, + temperature: 0, + // Ein nachdenkendes Modell braucht Platz, sonst kommt nur das Nachdenken an (Rocket). + max_tokens: 6000, + messages: [ + { role: "system", content: system }, + { role: "user", content: user }, + ], + }), + }); + } catch { + throw new AiUnavailable("network"); + } + if (!res.ok) throw new AiUnavailable(`status ${res.status}`); + const data = (await res.json().catch(() => null)) as { choices?: { message?: { content?: string } }[] } | null; + return parseJsonReply(data?.choices?.[0]?.message?.content ?? ""); +} + +export const RECIPE_PROMPT = `You read recipes. Answer with one JSON object only, no prose: +{"title": string, "portions": number|null, "minutes": number|null, "ingredients": string[], "steps": string[]} +Rules: copy every ingredient line exactly as printed, with amount and unit, one line per ingredient. +Copy the steps in order, one entry per step, in the language of the recipe. Do not translate, do not invent +amounts, do not convert units. If something is missing, use null or an empty list. +If there is no recipe, answer {"title": "", "portions": null, "minutes": null, "ingredients": [], "steps": []}.`; + +const recipeReply = z.object({ + title: z.string().catch(""), + portions: z.number().nullable().catch(null), + minutes: z.number().nullable().catch(null), + ingredients: z.array(z.string()).catch([]), + steps: z.array(z.string()).catch([]), +}); + +/** Antwort des Modells → dieselbe Form wie der JSON-LD-Import, oder null ohne Rezept. */ +export function recipeFromReply(reply: unknown): RawRecipe | null { + const parsed = recipeReply.safeParse(reply); + if (!parsed.success) return null; + const r = parsed.data; + const title = r.title.trim().slice(0, 120); + const ingredients = r.ingredients.map((l) => l.trim()).filter(Boolean).slice(0, 60); + if (!title || !ingredients.length) return null; + const whole = (n: number | null, max: number) => (n && n > 0 && n <= max ? Math.round(n) : null); + return { + title, + yield: whole(r.portions, 30), + totalMinutes: whole(r.minutes, 1440), + ingredients, + steps: r.steps.map((s) => s.trim()).filter(Boolean).slice(0, 40), + image: null, + }; +} diff --git a/lib/backup.ts b/lib/backup.ts index d1ee4f4..f320dee 100644 --- a/lib/backup.ts +++ b/lib/backup.ts @@ -40,6 +40,7 @@ export const TABLES = [ "kudos", "helper_points", "achievements", + "household_ai", // Schlüssel verschlüsselt: gehört mit tresor.key zusammen ] as const; /** Bewusst nicht im Abzug, je mit Grund. */ diff --git a/lib/photos.ts b/lib/photos.ts index 006076c..e3fe33d 100644 --- a/lib/photos.ts +++ b/lib/photos.ts @@ -25,6 +25,21 @@ export async function storePhoto(householdId: string, dishId: string, file: File return storePhotoBytes(householdId, dishId, Buffer.from(await file.arrayBuffer())); } +/** Für das Bildmodell: gedreht, höchstens 1600 px, JPEG als data-URL, ohne Metadaten. Nichts wird gespeichert. */ +export async function imageForModel(file: File): Promise { + if (!ACCEPTED.includes(file.type) || file.size > MAX_BYTES || file.size === 0) throw new PhotoRejected(file.type); + try { + const jpg = await sharp(Buffer.from(await file.arrayBuffer())) + .rotate() + .resize({ width: 1600, height: 1600, fit: "inside", withoutEnlargement: true }) + .jpeg({ quality: 82 }) + .toBuffer(); + return `data:image/jpeg;base64,${jpg.toString("base64")}`; + } catch { + throw new PhotoRejected("decode"); + } +} + /** Dasselbe für Bytes, etwa das Bild einer importierten Rezeptseite. */ export async function storePhotoBytes(householdId: string, dishId: string, input: Buffer): Promise { if (input.byteLength === 0 || input.byteLength > MAX_BYTES) throw new PhotoRejected("size"); diff --git a/lib/recipe-draft.ts b/lib/recipe-draft.ts new file mode 100644 index 0000000..f5a2e32 --- /dev/null +++ b/lib/recipe-draft.ts @@ -0,0 +1,43 @@ +import "server-only"; +import { INPUT_UNITS } from "./dishes"; +import { allIngredients } from "./ingredients"; +import { matchLines, type RawRecipe } from "./recipe-import"; +import { toBase } from "./units"; + +// Ein gelesenes Rezept (JSON-LD, Textmodell oder Kochbuchfoto) → Entwurf für +// das Formular (components/dishes/dish-form.tsx). Gespeichert wird nichts. +export async function draftFromRecipe(recipe: RawRecipe, locale: string, extra: { sourceUrl?: string | null; imageUrl?: string | null } = {}) { + const lines = matchLines(recipe.ingredients, await allIngredients(), locale); + return { + title: recipe.title, + portions: recipe.yield ?? 4, + effortMinutes: recipe.totalMinutes, + sourceUrl: extra.sourceUrl ?? null, + imageUrl: extra.imageUrl ?? null, + ingredients: lines + .filter((l) => l.ingredient) + .map((l) => { + // Maße, die das Formular nicht anbietet (cl, Tasse), gleich in die Basiseinheit. + if (l.qty !== null && l.unit && !(INPUT_UNITS as readonly string[]).includes(l.unit)) { + return { ingredient: l.ingredient, qty: toBase(l.qty, l.unit, l.ingredient!.unit), unit: l.ingredient!.unit, note: l.note }; + } + return { ingredient: l.ingredient, qty: l.qty, unit: l.unit, note: l.note }; + }), + unmatched: lines.filter((l) => !l.ingredient).map((l) => l.raw), + steps: recipe.steps.map((text) => ({ text, timerMinutes: null })), + }; +} + +/** Sichtbarer Text einer Seite für das Textmodell, gekürzt. */ +export function pageText(html: string, max = 20_000): string { + return html + .replace(/<(script|style|noscript|svg|nav|footer|header)[\s\S]*?<\/\1>/gi, " ") + .replace(/|<\/(p|li|h\d|div|tr)>/gi, "\n") + .replace(/<[^>]+>/g, " ") + .replace(/ /g, " ") + .replace(/&/g, "&") + .replace(/[ \t]+/g, " ") + .replace(/\n\s*\n+/g, "\n") + .trim() + .slice(0, max); +} diff --git a/lib/vault.ts b/lib/vault.ts new file mode 100644 index 0000000..444f517 --- /dev/null +++ b/lib/vault.ts @@ -0,0 +1,57 @@ +import "server-only"; +import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto"; +import { chmod, mkdir, readFile, writeFile } from "node:fs/promises"; +import path from "node:path"; + +// Tresor für Geheimnisse in der Datenbank (Muster Rocket, tresor.key): +// AES-256-GCM, der Schlüssel liegt als Datei unter /app/data und überlebt so +// eine Deinstallation. **Abzug und tresor.key gehören zusammen** — wer nur +// die Sicherung hat, hat die Geheimnisse nicht. + +const VERSION = 1; +let cached: Buffer | null = null; + +function keyPath(): string { + return path.join(process.env.APP_DATA_DIR ?? path.join(process.cwd(), ".data"), "tresor.key"); +} + +async function key(): Promise { + if (cached) return cached; + const file = keyPath(); + try { + const k = await readFile(file); + if (k.length !== 32) throw new Error("tresor.key hat nicht 32 Byte"); + cached = k; + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; + await mkdir(path.dirname(file), { recursive: true }); + const k = randomBytes(32); + await writeFile(file, k, { mode: 0o600, flag: "wx" }).catch(async (e) => { + if ((e as NodeJS.ErrnoException).code !== "EEXIST") throw e; + }); + await chmod(file, 0o600).catch(() => {}); + cached = await readFile(file); + } + return cached!; +} + +/** Text verschlüsseln: Version (1) · Nonce (12) · Tag (16) · Geheimtext. */ +export async function seal(text: string): Promise { + const nonce = randomBytes(12); + const cipher = createCipheriv("aes-256-gcm", await key(), nonce); + const body = Buffer.concat([cipher.update(text, "utf8"), cipher.final()]); + return Buffer.concat([Buffer.from([VERSION]), nonce, cipher.getAuthTag(), body]); +} + +/** Entschlüsseln; wirft bei falschem Schlüssel oder veränderten Daten. */ +export async function unseal(data: Buffer): Promise { + if (data[0] !== VERSION || data.length < 29) throw new Error("vault: unknown format"); + const decipher = createDecipheriv("aes-256-gcm", await key(), data.subarray(1, 13)); + decipher.setAuthTag(data.subarray(13, 29)); + return Buffer.concat([decipher.update(data.subarray(29)), decipher.final()]).toString("utf8"); +} + +/** Nur für Tests: Schlüssel neu lesen. */ +export function forgetKeyForTests() { + cached = null; +} diff --git a/messages/de.json b/messages/de.json index 5fbb252..0949241 100644 --- a/messages/de.json +++ b/messages/de.json @@ -102,6 +102,38 @@ "roleHints": { "member": "wünschen, kochen, einkaufen, bewerten", "admin": "dazu Runden planen und freigeben, Gerichte und Läden pflegen, einladen" + }, + "ai": { + "title": "AI", + "intro": "Lunch fragt ein Sprachmodell auf deiner Box, etwa LiteLLM. Nichts geht in eine Cloud, die du hier nicht selbst einträgst.", + "ready": "Eingerichtet", + "notReady": "Nicht eingerichtet", + "summary": "Für Kochbuchfotos und Rezeptseiten ohne Rezeptdaten.", + "endpoint": "Adresse (OpenAI-kompatibel)", + "endpointHint": "Endet meist auf /v1.", + "visionModel": "Bildmodell", + "visionHint": "Liest Kochbuchfotos, etwa ein Qwen-VL.", + "textModel": "Textmodell", + "textHint": "Liest Rezeptseiten ohne Rezeptdaten. Optional.", + "apiKey": "Schlüssel", + "keyStored": "Hinterlegt. Leer lassen, um ihn zu behalten.", + "keyOptional": "Optional", + "removeKey": "Schlüssel entfernen", + "save": "Speichern", + "saved": "Gespeichert.", + "test": "Verbindung prüfen", + "removeAll": "AI-Einstellung entfernen", + "errors": { + "invalid": "Bitte prüf die Adresse: Sie beginnt mit http:// oder https://." + }, + "check": { + "ok": "Verbunden. Die Modelle sind da.", + "modelMissing": "Verbunden, aber ein Modell fehlt. Vorhanden: {models}", + "unreachable": "Die Adresse ist nicht erreichbar.", + "key": "Der Schlüssel wurde abgelehnt.", + "status": "Der Dienst hat mit einem Fehler geantwortet.", + "aiNotConfigured": "Bitte zuerst speichern." + } } }, "nav": { @@ -219,7 +251,8 @@ "unknown": "Das hat nicht geklappt. Bitte versuch es noch einmal.", "missingAmount": "Bei einer Zutat fehlt die Menge. Trag sie ein oder entferne die Zeile." }, - "unmatched": "Diese Zeilen konnten wir keiner Zutat zuordnen. Füge sie bei Bedarf selbst hinzu:" + "unmatched": "Diese Zeilen konnten wir keiner Zutat zuordnen. Füge sie bei Bedarf selbst hinzu:", + "byAi": "Von der AI gelesen. Prüf jede Zutat und Menge, bevor du speicherst." }, "addLinkText": "Wir lesen Zutaten und Schritte von der Rezeptseite.", "link": { @@ -233,6 +266,27 @@ "url": "Diese Adresse können wir nicht öffnen. Bitte gib einen öffentlichen Link (https://…) an.", "unreachable": "Die Seite war nicht erreichbar. Versuch es später noch einmal.", "noRecipe": "Auf dieser Seite haben wir kein Rezept gefunden. Leg das Gericht lieber von Hand an.", + "unknown": "Das hat nicht geklappt. Bitte versuch es noch einmal.", + "aiUnavailable": "Die AI ist gerade nicht erreichbar. Versuch es später noch einmal oder leg das Gericht von Hand an." + } + }, + "addPhotoText": "Die AI liest Zutaten und Schritte von der Seite ab.", + "photo": { + "title": "Kochbuch fotografieren", + "choose": "Seite fotografieren", + "chosen": "{n, plural, one {1 Foto gewählt} other {# Fotos gewählt}}", + "chooseHint": "Eine Rezeptseite, höchstens zwei Fotos. Das Foto wird nicht gespeichert.", + "read": "Rezept lesen", + "reading": "Die AI liest …", + "readingHint": "Das kann eine Minute dauern.", + "notConfigured": "Für Fotos braucht Lunch ein Bildmodell. Das richtet ein Admin unter „Mehr“ ein.", + "setUp": "AI einrichten", + "askAdmin": "Bitte frag einen Admin im Haushalt.", + "errors": { + "photo": "Dieses Bild können wir nicht lesen. Bitte nimm ein JPEG-, PNG- oder HEIC-Foto.", + "noRecipe": "Auf dem Foto haben wir kein Rezept erkannt. Versuch es mit mehr Licht und der ganzen Seite im Bild.", + "aiUnavailable": "Die AI ist gerade nicht erreichbar. Versuch es später noch einmal.", + "aiNotConfigured": "Die AI ist nicht eingerichtet.", "unknown": "Das hat nicht geklappt. Bitte versuch es noch einmal." } } diff --git a/messages/en.json b/messages/en.json index aab2404..4199717 100644 --- a/messages/en.json +++ b/messages/en.json @@ -102,6 +102,38 @@ "roleHints": { "member": "wish, cook, shop, rate", "admin": "also plan and approve rounds, manage dishes and stores, invite" + }, + "ai": { + "title": "AI", + "intro": "Lunch asks a language model on your box, such as LiteLLM. Nothing goes to a cloud you do not enter here yourself.", + "ready": "Set up", + "notReady": "Not set up", + "summary": "For cookbook photos and recipe pages without recipe data.", + "endpoint": "Address (OpenAI-compatible)", + "endpointHint": "Usually ends in /v1.", + "visionModel": "Image model", + "visionHint": "Reads cookbook photos, for example a Qwen-VL.", + "textModel": "Text model", + "textHint": "Reads recipe pages without recipe data. Optional.", + "apiKey": "Key", + "keyStored": "Stored. Leave empty to keep it.", + "keyOptional": "Optional", + "removeKey": "Remove key", + "save": "Save", + "saved": "Saved.", + "test": "Check connection", + "removeAll": "Remove AI setting", + "errors": { + "invalid": "Please check the address: it starts with http:// or https://." + }, + "check": { + "ok": "Connected. The models are there.", + "modelMissing": "Connected, but a model is missing. Available: {models}", + "unreachable": "The address cannot be reached.", + "key": "The key was refused.", + "status": "The service answered with an error.", + "aiNotConfigured": "Please save first." + } } }, "nav": { @@ -219,7 +251,8 @@ "unknown": "That didn't work. Please try again.", "missingAmount": "An ingredient has no amount. Enter it or remove the row." }, - "unmatched": "We could not match these lines to an ingredient. Add them yourself if needed:" + "unmatched": "We could not match these lines to an ingredient. Add them yourself if needed:", + "byAi": "Read by the AI. Check every ingredient and amount before you save." }, "addLinkText": "We read ingredients and steps from the recipe page.", "link": { @@ -233,6 +266,27 @@ "url": "We cannot open this address. Please use a public link (https://…).", "unreachable": "The page could not be reached. Please try again later.", "noRecipe": "We found no recipe on this page. Better add the dish by hand.", + "unknown": "That did not work. Please try again.", + "aiUnavailable": "The AI cannot be reached right now. Try again later or add the dish by hand." + } + }, + "addPhotoText": "The AI reads ingredients and steps from the page.", + "photo": { + "title": "Photograph a cookbook", + "choose": "Take a photo of the page", + "chosen": "{n, plural, one {1 photo chosen} other {# photos chosen}}", + "chooseHint": "One recipe page, at most two photos. The photo is not kept.", + "read": "Read recipe", + "reading": "The AI is reading …", + "readingHint": "This can take a minute.", + "notConfigured": "Photos need an image model. An admin sets it up under “More”.", + "setUp": "Set up AI", + "askAdmin": "Please ask an admin in your household.", + "errors": { + "photo": "We cannot read this image. Please use a JPEG, PNG or HEIC photo.", + "noRecipe": "We found no recipe in the photo. Try more light and the whole page in the picture.", + "aiUnavailable": "The AI cannot be reached right now. Please try again later.", + "aiNotConfigured": "The AI is not set up.", "unknown": "That did not work. Please try again." } } diff --git a/messages/es.json b/messages/es.json index 5770e53..f7335e7 100644 --- a/messages/es.json +++ b/messages/es.json @@ -102,6 +102,38 @@ "roleHints": { "member": "wish, cook, shop, rate", "admin": "also plan and approve rounds, manage dishes and stores, invite" + }, + "ai": { + "title": "AI", + "intro": "Lunch asks a language model on your box, such as LiteLLM. Nothing goes to a cloud you do not enter here yourself.", + "ready": "Set up", + "notReady": "Not set up", + "summary": "For cookbook photos and recipe pages without recipe data.", + "endpoint": "Address (OpenAI-compatible)", + "endpointHint": "Usually ends in /v1.", + "visionModel": "Image model", + "visionHint": "Reads cookbook photos, for example a Qwen-VL.", + "textModel": "Text model", + "textHint": "Reads recipe pages without recipe data. Optional.", + "apiKey": "Key", + "keyStored": "Stored. Leave empty to keep it.", + "keyOptional": "Optional", + "removeKey": "Remove key", + "save": "Save", + "saved": "Saved.", + "test": "Check connection", + "removeAll": "Remove AI setting", + "errors": { + "invalid": "Please check the address: it starts with http:// or https://." + }, + "check": { + "ok": "Connected. The models are there.", + "modelMissing": "Connected, but a model is missing. Available: {models}", + "unreachable": "The address cannot be reached.", + "key": "The key was refused.", + "status": "The service answered with an error.", + "aiNotConfigured": "Please save first." + } } }, "nav": { @@ -219,7 +251,8 @@ "unknown": "That didn't work. Please try again.", "missingAmount": "A un ingrediente le falta la cantidad. Escríbela o quita la fila." }, - "unmatched": "No pudimos asignar estas líneas a un ingrediente. Añádelas tú si hace falta:" + "unmatched": "No pudimos asignar estas líneas a un ingrediente. Añádelas tú si hace falta:", + "byAi": "Read by the AI. Check every ingredient and amount before you save." }, "addLinkText": "Leemos los ingredientes y los pasos de la página de la receta.", "link": { @@ -233,7 +266,28 @@ "url": "No podemos abrir esta dirección. Usa un enlace público (https://…).", "unreachable": "No se pudo acceder a la página. Inténtalo más tarde.", "noRecipe": "No encontramos ninguna receta en esta página. Mejor añade el plato a mano.", - "unknown": "No ha funcionado. Inténtalo de nuevo." + "unknown": "No ha funcionado. Inténtalo de nuevo.", + "aiUnavailable": "The AI cannot be reached right now. Try again later or add the dish by hand." + } + }, + "addPhotoText": "The AI reads ingredients and steps from the page.", + "photo": { + "title": "Photograph a cookbook", + "choose": "Take a photo of the page", + "chosen": "{n, plural, one {1 photo chosen} other {# photos chosen}}", + "chooseHint": "One recipe page, at most two photos. The photo is not kept.", + "read": "Read recipe", + "reading": "The AI is reading …", + "readingHint": "This can take a minute.", + "notConfigured": "Photos need an image model. An admin sets it up under “More”.", + "setUp": "Set up AI", + "askAdmin": "Please ask an admin in your household.", + "errors": { + "photo": "We cannot read this image. Please use a JPEG, PNG or HEIC photo.", + "noRecipe": "We found no recipe in the photo. Try more light and the whole page in the picture.", + "aiUnavailable": "The AI cannot be reached right now. Please try again later.", + "aiNotConfigured": "The AI is not set up.", + "unknown": "That did not work. Please try again." } } } diff --git a/messages/fr.json b/messages/fr.json index 25d4474..021582f 100644 --- a/messages/fr.json +++ b/messages/fr.json @@ -102,6 +102,38 @@ "roleHints": { "member": "wish, cook, shop, rate", "admin": "also plan and approve rounds, manage dishes and stores, invite" + }, + "ai": { + "title": "AI", + "intro": "Lunch asks a language model on your box, such as LiteLLM. Nothing goes to a cloud you do not enter here yourself.", + "ready": "Set up", + "notReady": "Not set up", + "summary": "For cookbook photos and recipe pages without recipe data.", + "endpoint": "Address (OpenAI-compatible)", + "endpointHint": "Usually ends in /v1.", + "visionModel": "Image model", + "visionHint": "Reads cookbook photos, for example a Qwen-VL.", + "textModel": "Text model", + "textHint": "Reads recipe pages without recipe data. Optional.", + "apiKey": "Key", + "keyStored": "Stored. Leave empty to keep it.", + "keyOptional": "Optional", + "removeKey": "Remove key", + "save": "Save", + "saved": "Saved.", + "test": "Check connection", + "removeAll": "Remove AI setting", + "errors": { + "invalid": "Please check the address: it starts with http:// or https://." + }, + "check": { + "ok": "Connected. The models are there.", + "modelMissing": "Connected, but a model is missing. Available: {models}", + "unreachable": "The address cannot be reached.", + "key": "The key was refused.", + "status": "The service answered with an error.", + "aiNotConfigured": "Please save first." + } } }, "nav": { @@ -219,7 +251,8 @@ "unknown": "That didn't work. Please try again.", "missingAmount": "Il manque la quantité d’un ingrédient. Indique-la ou supprime la ligne." }, - "unmatched": "Nous n’avons pas pu associer ces lignes à un ingrédient. Ajoute-les toi-même si besoin :" + "unmatched": "Nous n’avons pas pu associer ces lignes à un ingrédient. Ajoute-les toi-même si besoin :", + "byAi": "Read by the AI. Check every ingredient and amount before you save." }, "addLinkText": "Nous lisons les ingrédients et les étapes sur la page de la recette.", "link": { @@ -233,7 +266,28 @@ "url": "Nous ne pouvons pas ouvrir cette adresse. Utilise un lien public (https://…).", "unreachable": "La page est injoignable. Réessaie plus tard.", "noRecipe": "Aucune recette trouvée sur cette page. Ajoute plutôt le plat à la main.", - "unknown": "Cela n’a pas marché. Réessaie." + "unknown": "Cela n’a pas marché. Réessaie.", + "aiUnavailable": "The AI cannot be reached right now. Try again later or add the dish by hand." + } + }, + "addPhotoText": "The AI reads ingredients and steps from the page.", + "photo": { + "title": "Photograph a cookbook", + "choose": "Take a photo of the page", + "chosen": "{n, plural, one {1 photo chosen} other {# photos chosen}}", + "chooseHint": "One recipe page, at most two photos. The photo is not kept.", + "read": "Read recipe", + "reading": "The AI is reading …", + "readingHint": "This can take a minute.", + "notConfigured": "Photos need an image model. An admin sets it up under “More”.", + "setUp": "Set up AI", + "askAdmin": "Please ask an admin in your household.", + "errors": { + "photo": "We cannot read this image. Please use a JPEG, PNG or HEIC photo.", + "noRecipe": "We found no recipe in the photo. Try more light and the whole page in the picture.", + "aiUnavailable": "The AI cannot be reached right now. Please try again later.", + "aiNotConfigured": "The AI is not set up.", + "unknown": "That did not work. Please try again." } } } diff --git a/olares/Chart.yaml b/olares/Chart.yaml index 54f9f7a..5df8228 100644 --- a/olares/Chart.yaml +++ b/olares/Chart.yaml @@ -2,5 +2,5 @@ apiVersion: v2 name: lunch description: Was gibt's? — die Familie entscheidet gemeinsam, was es gibt; aus dem Plan entsteht die Einkaufsliste type: application -version: 26.11.6 # YY.M. wie im AImighty-Markt — bei jeder Chart-Änderung erhöhen -appVersion: "26.11.6" # MUSS gleich version sein: der Linter prüft es, und der Image-Tag hängt daran +version: 26.11.7 # YY.M. wie im AImighty-Markt — bei jeder Chart-Änderung erhöhen +appVersion: "26.11.7" # MUSS gleich version sein: der Linter prüft es, und der Image-Tag hängt daran diff --git a/olares/OlaresManifest.yaml b/olares/OlaresManifest.yaml index 48b9289..da61aa7 100644 --- a/olares/OlaresManifest.yaml +++ b/olares/OlaresManifest.yaml @@ -21,7 +21,7 @@ metadata: title: What's cooking? description: The family decides together what's for dinner — and the shopping list writes itself. Runs entirely on your own box. icon: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png - version: 26.11.6 + version: 26.11.7 categories: - Applications @@ -61,7 +61,7 @@ permission: appData: true spec: - versionName: '26.11.6' + versionName: '26.11.7' featuredImage: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png promoteImage: diff --git a/olares/markt/26.11.7.md b/olares/markt/26.11.7.md new file mode 100644 index 0000000..ac6c055 --- /dev/null +++ b/olares/markt/26.11.7.md @@ -0,0 +1,5 @@ +# Cookbook photos +v26.11.7: Photograph a cookbook page and Lunch reads title, ingredients and steps into a draft you check before saving. The reading is done by a language model on your own box, set up by an admin under More › AI (address, image model, optional text model, key stored encrypted). Recipe pages without recipe data are read by the text model. Nothing goes to a cloud you did not enter yourself, and every draft read by the AI is marked as such. + +## Deutsch +v26.11.7: Eine Kochbuchseite fotografieren, und Lunch trägt Titel, Zutaten und Schritte als Entwurf ein, den du vor dem Speichern prüfst. Gelesen wird von einem Sprachmodell auf deiner eigenen Box, das ein Admin unter Mehr › AI einrichtet (Adresse, Bildmodell, optional Textmodell, Schlüssel verschlüsselt gespeichert). Rezeptseiten ohne Rezeptdaten liest das Textmodell. Nichts geht in eine Cloud, die du nicht selbst eingetragen hast, und jeder Entwurf der AI ist als solcher gekennzeichnet. diff --git a/tests/ai.test.ts b/tests/ai.test.ts new file mode 100644 index 0000000..2bf9ed8 --- /dev/null +++ b/tests/ai.test.ts @@ -0,0 +1,52 @@ +import { createServer, type Server } from "node:http"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; + +vi.mock("server-only", () => ({})); +vi.mock("@/lib/vault", () => ({ unseal: async () => "sk-test" })); + +// lib/ai.ts gegen einen kleinen Server in OpenAI-Form. +describe("ai", () => { + let server: Server; + let endpoint = ""; + const seen: { auth?: string; body?: Record }[] = []; + let ai: typeof import("@/lib/ai"); + + beforeAll(async () => { + ai = await import("@/lib/ai"); + server = createServer((req, res) => { + let raw = ""; + req.on("data", (c) => (raw += c)); + req.on("end", () => { + seen.push({ auth: req.headers.authorization, body: raw ? JSON.parse(raw) : undefined }); + if (req.headers.authorization !== "Bearer sk-test") return res.writeHead(401).end(); + if (req.url === "/v1/models") return res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ data: [{ id: "qwen-vl" }] })); + const content = 'hm```json\n{"title":"Linsensuppe","portions":4,"minutes":30,"ingredients":["250 g rote Linsen"],"steps":["Kochen."]}\n```'; + res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ choices: [{ message: { content } }] })); + }); + }); + await new Promise((done) => server.listen(0, "127.0.0.1", done)); + endpoint = `http://127.0.0.1:${(server.address() as { port: number }).port}/v1/`; + }); + afterAll(() => new Promise((done) => server.close(() => done()))); + + const settings = () => ({ endpoint, textModel: "qwen-text", visionModel: "qwen-vl", apiKeyEnc: Buffer.from([1]) }); + + it("checks the connection and which models exist", async () => { + expect(await ai.checkConnection(settings())).toEqual({ ok: true, models: ["qwen-vl"], textFound: false, visionFound: true }); + expect(await ai.checkConnection({ ...settings(), apiKeyEnc: null })).toEqual({ ok: false, reason: "key" }); + expect(await ai.checkConnection({ ...settings(), endpoint: "http://127.0.0.1:9/v1" })).toEqual({ ok: false, reason: "unreachable" }); + }); + + it("asks the vision model and reads a recipe from the reply", async () => { + const reply = await ai.askJson(settings(), "vision", ai.RECIPE_PROMPT, [{ type: "text", text: "Rezept" }]); + expect(seen.at(-1)!.body!.model).toBe("qwen-vl"); + expect(ai.recipeFromReply(reply)).toMatchObject({ title: "Linsensuppe", yield: 4, totalMinutes: 30, ingredients: ["250 g rote Linsen"] }); + }); + + it("refuses without a model, and treats empty or broken replies as no recipe", async () => { + await expect(ai.askJson({ ...settings(), textModel: null }, "text", "x", "y")).rejects.toBeInstanceOf(ai.AiNotConfigured); + expect(ai.parseJsonReply("kein JSON")).toBeNull(); + expect(ai.recipeFromReply({ title: "", ingredients: [] })).toBeNull(); + expect(ai.recipeFromReply({ title: "X", ingredients: ["1 Ei"], portions: 9000 })).toMatchObject({ yield: null }); + }); +}); diff --git a/tests/fixture.ts b/tests/fixture.ts index 019ac15..7b248c2 100644 --- a/tests/fixture.ts +++ b/tests/fixture.ts @@ -7,7 +7,7 @@ export const SEEDED_TABLES = [ "households", "members", "passkeys", "sessions", "invitations", "stores", "store_aisles", "dishes", "dish_ingredients", "dish_steps", "dish_translations", "rounds", "wishes", "slots", "shopping_items", "pantry_staples", "receipts", "receipt_lines", "ingredient_aliases", "price_points", "ratings", "kudos", - "helper_points", "achievements", + "helper_points", "achievements", "household_ai", ]; /** Eine globale Zutat, wie sie eine Seed-Migration anlegt. */ @@ -84,6 +84,7 @@ export async function seedHousehold(client: pg.Client | pg.PoolClient, h: string await q("insert into kudos (household_id, slot_id, from_member_id) values ($1, $2, $3)", [h, slot, member]); await q("insert into helper_points (household_id, member_id, points, granted_by) values ($1, $2, 1, $2)", [h, member]); await q("insert into achievements (household_id, key) values ($1, 'first_round')", [h]); + await q("insert into household_ai (household_id, endpoint, vision_model, updated_by) values ($1, 'http://llm.test/v1', 'vision', $2)", [h, member]); await q("commit"); return { dish, member }; } diff --git a/tests/vault.test.ts b/tests/vault.test.ts new file mode 100644 index 0000000..c1b4825 --- /dev/null +++ b/tests/vault.test.ts @@ -0,0 +1,27 @@ +import { mkdtempSync, statSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { describe, expect, it, vi } from "vitest"; + +vi.mock("server-only", () => ({})); + +describe("vault", () => { + it("seals and opens, refuses tampering and a foreign key", async () => { + const dir = mkdtempSync(path.join(tmpdir(), "lunch-vault-")); + process.env.APP_DATA_DIR = dir; + const vault = await import("@/lib/vault"); + vault.forgetKeyForTests(); + const sealed = await vault.seal("sk-geheim"); + expect(sealed.toString("utf8")).not.toContain("sk-geheim"); + expect(await vault.unseal(sealed)).toBe("sk-geheim"); + expect(statSync(path.join(dir, "tresor.key")).mode & 0o777).toBe(0o600); + + const tampered = Buffer.from(sealed); + tampered[tampered.length - 1]! ^= 1; + await expect(vault.unseal(tampered)).rejects.toThrow(); + + writeFileSync(path.join(dir, "tresor.key"), Buffer.alloc(32, 7)); + vault.forgetKeyForTests(); + await expect(vault.unseal(sealed)).rejects.toThrow(); + }); +});