diff --git a/CLAUDE.md b/CLAUDE.md index 72e813b..85a8fa1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -248,6 +248,13 @@ Vorlagen ersetzt. `tests/seed.test.ts` prüft die Dateien. Ein Haushalt - **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. +- **Olares Router** (seit 26.11.10, `lib/olares-router.ts`): Auf Olares bietet die App + „Router“ ein Modell für alle Apps an, `default-chat` meint den dort gewählten + Standard. Seine Adresse ist `https://1a9c83350./v1` — Lunch leitet + sie aus der eigenen Adresse ab und bietet „Olares Router verwenden“ an; gespeichert + wird erst, wenn der Router antwortet. Kein stiller Vorgabewert. +- „Verbindung prüfen“ erkennt eine Anmeldeseite (Weiterleitung oder HTML statt + JSON) und sagt das, statt „Modell fehlt“. - 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` diff --git a/OlaresManifest.yaml b/OlaresManifest.yaml index 9ed5201..cf17332 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.9 + version: 26.11.10 categories: - Applications @@ -61,7 +61,7 @@ permission: appData: true spec: - versionName: '26.11.9' + versionName: '26.11.10' 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 index 67b861a..f7da94e 100644 --- a/app/(app)/gerichte/foto/page.tsx +++ b/app/(app)/gerichte/foto/page.tsx @@ -5,7 +5,10 @@ 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"; +import { UseRouter } from "@/components/more/use-router"; +import { loadInstance } from "@/lib/auth/webauthn"; +import { withAuth, withHousehold } from "@/lib/db"; +import { routerEndpoint } from "@/lib/olares-router"; export const dynamic = "force-dynamic"; @@ -14,6 +17,8 @@ export default async function PhotoDishPage() { if (session.role !== "admin" && session.role !== "member") redirect("/gerichte"); const t = await getTranslations("dishes"); const ai = await withHousehold(session.householdId, loadAi); + const instance = await withAuth(loadInstance); + const router = instance ? routerEndpoint(instance.origin) : null; return (
@@ -25,6 +30,7 @@ export default async function PhotoDishPage() { ) : (

{t("photo.notConfigured")}

+ {session.role === "admin" && router ? : null} {session.role === "admin" ? ( diff --git a/app/(app)/mehr/ki/page.tsx b/app/(app)/mehr/ki/page.tsx index fd50bcb..c2e635a 100644 --- a/app/(app)/mehr/ki/page.tsx +++ b/app/(app)/mehr/ki/page.tsx @@ -3,7 +3,10 @@ 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"; +import { UseRouter } from "@/components/more/use-router"; +import { loadInstance } from "@/lib/auth/webauthn"; +import { withAuth, withHousehold } from "@/lib/db"; +import { routerEndpoint } from "@/lib/olares-router"; export const dynamic = "force-dynamic"; @@ -12,6 +15,8 @@ export default async function AiSettingsPage() { if (session.role !== "admin") redirect("/mehr"); const t = await getTranslations("more.ai"); const ai = await withHousehold(session.householdId, loadAi); + const instance = await withAuth(loadInstance); + const router = instance ? routerEndpoint(instance.origin) : null; return (
@@ -19,6 +24,7 @@ export default async function AiSettingsPage() {

{t("title")}

{t("intro")}

+ {router && ai?.endpoint !== router ? : null} diff --git a/app/api/ai/router/route.ts b/app/api/ai/router/route.ts new file mode 100644 index 0000000..99419f5 --- /dev/null +++ b/app/api/ai/router/route.ts @@ -0,0 +1,30 @@ +import { checkConnection } from "@/lib/ai"; +import { guardWrite, isResponse } from "@/lib/auth/guard"; +import { fail, json } from "@/lib/auth/http"; +import { loadInstance } from "@/lib/auth/webauthn"; +import { withAuth, withHousehold } from "@/lib/db"; +import { ROUTER_MODEL, routerEndpoint } from "@/lib/olares-router"; + +export const dynamic = "force-dynamic"; + +// „Olares Router verwenden“: Adresse aus der eigenen Adresse ableiten, prüfen, +// und nur wenn der Router antwortet, als AI-Einstellung speichern (lib/olares-router.ts). +export async function POST(request: Request) { + const session = await guardWrite(request, ["admin"]); + if (isResponse(session)) return session; + const instance = await withAuth(loadInstance); + const endpoint = instance ? routerEndpoint(instance.origin) : null; + if (!endpoint) return fail("noRouter", 404); + const check = await checkConnection({ endpoint, textModel: ROUTER_MODEL, visionModel: ROUTER_MODEL, apiKeyEnc: null }); + if (!check.ok) return json(check, 422); + 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, $3, null, $4) + on conflict (household_id) do update set endpoint = $2, text_model = $3, vision_model = $3, api_key_enc = null, + updated_by = $4, updated_at = now()`, + [session.householdId, endpoint, ROUTER_MODEL, session.memberId], + ), + ); + return json({ ...check, endpoint }); +} diff --git a/components/more/ai-settings.tsx b/components/more/ai-settings.tsx index 1653e6a..0def81a 100644 --- a/components/more/ai-settings.tsx +++ b/components/more/ai-settings.tsx @@ -11,7 +11,7 @@ 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" }; + | { ok: false; reason: "unreachable" | "key" | "status" | "login" | "aiNotConfigured" }; // AI-Einstellung (nur Admin). Keine vorgegebene Adresse: Die Box kennt ihre eigene. export function AiSettings({ current }: { current: Current }) { diff --git a/components/more/use-router.tsx b/components/more/use-router.tsx new file mode 100644 index 0000000..0a56ed2 --- /dev/null +++ b/components/more/use-router.tsx @@ -0,0 +1,41 @@ +"use client"; + +import { Router } from "lucide-react"; +import { useRouter } from "next/navigation"; +import { useTranslations } from "next-intl"; +import { useState } from "react"; +import { Button } from "@/components/ui/button"; +import { ErrorNotice } from "@/components/ui/notice"; + +// „Olares Router verwenden“: ein Tipp, Lunch prüft den Router der Box und +// speichert ihn nur, wenn er antwortet (app/api/ai/router). +export function UseRouter({ endpoint }: { endpoint: string }) { + const t = useTranslations("more.ai"); + const router = useRouter(); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + return ( +
+

{t("routerTitle")}

+

{t("routerText", { endpoint })}

+ {error ? {t(`check.${error}`)} : null} + +
+ ); +} diff --git a/lib/ai.ts b/lib/ai.ts index 31799bd..280f1d1 100644 --- a/lib/ai.ts +++ b/lib/ai.ts @@ -2,6 +2,7 @@ import "server-only"; import type pg from "pg"; import { z } from "zod"; import type { RawRecipe } from "./recipe-import"; +import { isRouterAlias } from "./olares-router"; import { unseal } from "./vault"; // AI über einen OpenAI-kompatiblen Endpunkt (LiteLLM auf der Box, Konzept @@ -38,21 +39,29 @@ async function headers(settings: AiSettings): Promise> { export type ConnectionCheck = | { ok: true; models: string[]; textFound: boolean | null; visionFound: boolean | null } - | { ok: false; reason: "unreachable" | "key" | "status" }; + | { ok: false; reason: "unreachable" | "key" | "status" | "login" }; /** „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) }); + res = await fetch(`${base(settings.endpoint)}/models`, { + headers: await headers(settings), + redirect: "manual", + signal: AbortSignal.timeout(10_000), + }); } catch { return { ok: false, reason: "unreachable" }; } + // Eine Weiterleitung oder eine HTML-Seite heißt: Vor dem Dienst sitzt eine + // Anmeldung (bei Olares der Zugang von außen statt der Adresse für Apps). + if (res.status >= 300 && res.status < 400) return { ok: false, reason: "login" }; if (res.status === 401 || res.status === 403) return { ok: false, reason: "key" }; if (!res.ok) return { ok: false, reason: "status" }; + if (!/json/.test(res.headers.get("content-type") ?? "")) return { ok: false, reason: "login" }; 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); + const has = (m: string | null) => (m ? models.includes(m) || isRouterAlias(m) : null); return { ok: true, models, textFound: has(settings.textModel), visionFound: has(settings.visionModel) }; } diff --git a/lib/olares-router.ts b/lib/olares-router.ts new file mode 100644 index 0000000..b56c3a8 --- /dev/null +++ b/lib/olares-router.ts @@ -0,0 +1,26 @@ +// Der Router von Olares (App „Router“) bietet allen Apps der Box ein Sprachmodell +// an, OpenAI-kompatibel; `default-chat` meint das Modell, das dort als Standard +// gewählt ist. Seine Adresse folgt dem Schema der Olares-Zugänge: +// . — für den Router immer 1a9c8335 + 0 (Kai, 6.11.2026). Lunch leitet +// sie aus seiner eigenen Adresse ab und schlägt sie nur vor; gespeichert wird +// sie erst, wenn „Verbindung prüfen“ grün war. + +const ROUTER_ENTRANCE = "1a9c83350"; +export const ROUTER_MODEL = "default-chat"; + +/** Router-Adresse zur Adresse von Lunch, oder null, wenn Lunch nicht auf Olares läuft. */ +export function routerEndpoint(origin: string): string | null { + let host: string; + try { + host = new URL(origin).hostname; + } catch { + return null; + } + const [first, ...rest] = host.split("."); + if (!first || !/^[0-9a-f]{8}\d{1,2}$/.test(first) || rest.length < 2) return null; + return `https://${ROUTER_ENTRANCE}.${rest.join(".")}/v1`; +} + +/** Namen, die der Router selbst auflöst und die deshalb nicht in /models stehen. */ +export const isRouterAlias = (model: string) => /^default-[a-z]+$/.test(model); diff --git a/messages/de.json b/messages/de.json index 1e47587..a6502a7 100644 --- a/messages/de.json +++ b/messages/de.json @@ -144,8 +144,13 @@ "unreachable": "Die Adresse ist nicht erreichbar.", "key": "Der Schlüssel wurde abgelehnt.", "status": "Der Dienst hat mit einem Fehler geantwortet.", - "aiNotConfigured": "Bitte zuerst speichern." - } + "aiNotConfigured": "Bitte zuerst speichern.", + "login": "Statt des Dienstes hat eine Anmeldeseite geantwortet. Lunch braucht die Adresse für „Apps in Olares“." + }, + "routerTitle": "Olares Router gefunden", + "routerText": "Deine Box bietet über den Router ein Sprachmodell an ({endpoint}). Lunch nimmt das Standardmodell (default-chat) für Text und Fotos.", + "routerUse": "Olares Router verwenden", + "routerChecking": "Prüft den Router …" }, "kids": { "title": "Kinder", diff --git a/messages/en.json b/messages/en.json index da1fa08..ec4a7ad 100644 --- a/messages/en.json +++ b/messages/en.json @@ -144,8 +144,13 @@ "unreachable": "The address cannot be reached.", "key": "The key was refused.", "status": "The service answered with an error.", - "aiNotConfigured": "Please save first." - } + "aiNotConfigured": "Please save first.", + "login": "A sign-in page answered instead of the service. Lunch needs the address for “Apps in Olares”." + }, + "routerTitle": "Olares Router found", + "routerText": "Your box offers a language model through the Router ({endpoint}). Lunch uses its default model (default-chat) for text and photos.", + "routerUse": "Use Olares Router", + "routerChecking": "Checking the Router …" }, "kids": { "title": "Children", diff --git a/messages/es.json b/messages/es.json index e85b899..b3c0e65 100644 --- a/messages/es.json +++ b/messages/es.json @@ -144,8 +144,13 @@ "unreachable": "The address cannot be reached.", "key": "The key was refused.", "status": "The service answered with an error.", - "aiNotConfigured": "Please save first." - } + "aiNotConfigured": "Please save first.", + "login": "A sign-in page answered instead of the service. Lunch needs the address for “Apps in Olares”." + }, + "routerTitle": "Olares Router found", + "routerText": "Your box offers a language model through the Router ({endpoint}). Lunch uses its default model (default-chat) for text and photos.", + "routerUse": "Use Olares Router", + "routerChecking": "Checking the Router …" }, "kids": { "title": "Children", diff --git a/messages/fr.json b/messages/fr.json index e662d56..ca96854 100644 --- a/messages/fr.json +++ b/messages/fr.json @@ -144,8 +144,13 @@ "unreachable": "The address cannot be reached.", "key": "The key was refused.", "status": "The service answered with an error.", - "aiNotConfigured": "Please save first." - } + "aiNotConfigured": "Please save first.", + "login": "A sign-in page answered instead of the service. Lunch needs the address for “Apps in Olares”." + }, + "routerTitle": "Olares Router found", + "routerText": "Your box offers a language model through the Router ({endpoint}). Lunch uses its default model (default-chat) for text and photos.", + "routerUse": "Use Olares Router", + "routerChecking": "Checking the Router …" }, "kids": { "title": "Children", diff --git a/olares/Chart.yaml b/olares/Chart.yaml index 37453ae..3193603 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.9 # YY.M. wie im AImighty-Markt — bei jeder Chart-Änderung erhöhen -appVersion: "26.11.9" # MUSS gleich version sein: der Linter prüft es, und der Image-Tag hängt daran +version: 26.11.10 # YY.M. wie im AImighty-Markt — bei jeder Chart-Änderung erhöhen +appVersion: "26.11.10" # 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 9ed5201..cf17332 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.9 + version: 26.11.10 categories: - Applications @@ -61,7 +61,7 @@ permission: appData: true spec: - versionName: '26.11.9' + versionName: '26.11.10' featuredImage: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png promoteImage: diff --git a/olares/markt/26.11.10.md b/olares/markt/26.11.10.md new file mode 100644 index 0000000..dc383a1 --- /dev/null +++ b/olares/markt/26.11.10.md @@ -0,0 +1,5 @@ +# AI from the Olares Router +v26.11.10: On Olares, Lunch now finds the box's Router and offers it with one tap under More › AI and on the cookbook photo page. It checks the Router first and only then saves it, using the default model you chose in the Router for text and photos. The connection check also recognises when a sign-in page answers instead of the model service and says so. + +## Deutsch +v26.11.10: Auf Olares findet Lunch jetzt den Router der Box und bietet ihn unter Mehr › AI und beim Kochbuchfoto mit einem Tipp an. Lunch prüft den Router zuerst und speichert ihn erst dann, mit dem Standardmodell, das du im Router gewählt hast, für Text und Fotos. Die Verbindungsprüfung erkennt außerdem, wenn statt des Modelldienstes eine Anmeldeseite antwortet, und sagt das. diff --git a/tests/ai.test.ts b/tests/ai.test.ts index 2bf9ed8..8045a47 100644 --- a/tests/ai.test.ts +++ b/tests/ai.test.ts @@ -18,6 +18,8 @@ describe("ai", () => { req.on("data", (c) => (raw += c)); req.on("end", () => { seen.push({ auth: req.headers.authorization, body: raw ? JSON.parse(raw) : undefined }); + if (req.url === "/login/v1/models") return res.writeHead(302, { location: "/anmeldung" }).end(); + if (req.url === "/html/v1/models") return res.writeHead(200, { "content-type": "text/html" }).end("Anmelden"); 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```'; @@ -35,6 +37,12 @@ describe("ai", () => { 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" }); + // Eine Anmeldeseite statt des Dienstes (Olares-Zugang von außen) wird erkannt. + const root = endpoint.replace(/\/v1\/$/, ""); + expect(await ai.checkConnection({ ...settings(), endpoint: `${root}/login/v1` })).toEqual({ ok: false, reason: "login" }); + expect(await ai.checkConnection({ ...settings(), endpoint: `${root}/html/v1` })).toEqual({ ok: false, reason: "login" }); + // default-chat löst der Olares-Router selbst auf. + expect(await ai.checkConnection({ ...settings(), textModel: "default-chat" })).toMatchObject({ ok: true, textFound: true }); }); it("asks the vision model and reads a recipe from the reply", async () => { diff --git a/tests/olares-router.test.ts b/tests/olares-router.test.ts new file mode 100644 index 0000000..5c124bd --- /dev/null +++ b/tests/olares-router.test.ts @@ -0,0 +1,20 @@ +import { describe, expect, it } from "vitest"; +import { isRouterAlias, routerEndpoint } from "@/lib/olares-router"; + +describe("olares router", () => { + it("derives the router address from the app's own Olares address", () => { + expect(routerEndpoint("https://ab12cd340.kaivostudio.olares.de")).toBe("https://1a9c83350.kaivostudio.olares.de/v1"); + expect(routerEndpoint("https://ab12cd341.someone.olares.com")).toBe("https://1a9c83350.someone.olares.com/v1"); + }); + + it("offers nothing outside Olares", () => { + expect(routerEndpoint("http://localhost:3020")).toBeNull(); + expect(routerEndpoint("https://lunch.example.org")).toBeNull(); + expect(routerEndpoint("kaputt")).toBeNull(); + }); + + it("knows the router's own model names", () => { + expect(isRouterAlias("default-chat")).toBe(true); + expect(isRouterAlias("Olares/qwen3.8-flash-next-xxs")).toBe(false); + }); +});