Compare commits

..
1 Commits
Author SHA1 Message Date
kai 1a75c6910c Offer the Olares Router as AI with one tap; detect sign-in pages (26.11.10) (#11)
release / which version (push) Successful in 1s
release / olares chart · sanity (push) Successful in 3s
release / app (push) Successful in 53s
release / tag and release (push) Successful in 2s
2026-11-06 22:57:14 +00:00
18 changed files with 198 additions and 20 deletions

No files matched your search

+7
View File
@@ -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.<Olares-Domain>/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); `<think>` und
Code-Zäune fallen beim Lesen weg (`parseJsonReply`).
- Der Schlüssel liegt verschlüsselt (`lib/vault.ts`, AES-256-GCM, `tresor.key`
+2 -2
View File
@@ -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:
+7 -1
View File
@@ -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 (
<main className="mx-auto flex max-w-md flex-col gap-5 px-4 py-6">
<header className="flex flex-col gap-1">
@@ -25,6 +30,7 @@ export default async function PhotoDishPage() {
) : (
<div className="flex flex-col gap-3 rounded-2xl border border-border p-4">
<p>{t("photo.notConfigured")}</p>
{session.role === "admin" && router ? <UseRouter endpoint={router} /> : null}
{session.role === "admin" ? (
<Link href="/mehr/ki" className="inline-flex min-h-11 items-center gap-2 font-semibold text-accent underline-offset-4 hover:underline">
<Settings aria-hidden className="size-5" strokeWidth={1.5} />
+7 -1
View File
@@ -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 (
<main className="mx-auto flex max-w-md flex-col gap-5 px-4 py-6">
<header className="flex flex-col gap-1">
@@ -19,6 +24,7 @@ export default async function AiSettingsPage() {
<h1 className="text-4xl leading-tight">{t("title")}</h1>
<p className="text-muted-foreground">{t("intro")}</p>
</header>
{router && ai?.endpoint !== router ? <UseRouter endpoint={router} /> : null}
<AiSettings
current={ai ? { endpoint: ai.endpoint, textModel: ai.textModel, visionModel: ai.visionModel, hasKey: !!ai.apiKeyEnc } : null}
/>
+30
View File
@@ -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 });
}
+1 -1
View File
@@ -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 }) {
+41
View File
@@ -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<string | null>(null);
return (
<div className="flex flex-col gap-3 rounded-2xl bg-muted p-4">
<p className="font-semibold">{t("routerTitle")}</p>
<p className="text-sm text-muted-foreground">{t("routerText", { endpoint })}</p>
{error ? <ErrorNotice>{t(`check.${error}`)}</ErrorNotice> : null}
<Button
type="button"
size="lg"
disabled={busy}
onClick={async () => {
setBusy(true);
setError(null);
const res = await fetch("/api/ai/router", { method: "POST" });
const data = await res.json().catch(() => ({}));
setBusy(false);
if (res.ok) router.refresh();
else setError(["unreachable", "key", "status", "login"].includes(data.reason) ? data.reason : "status");
}}
>
<Router aria-hidden />
{busy ? t("routerChecking") : t("routerUse")}
</Button>
</div>
);
}
+12 -3
View File
@@ -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<Record<string, string>> {
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<ConnectionCheck> {
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) };
}
+26
View File
@@ -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:
// <erste acht Zeichen des App-Hashes><Nummer des Zugangs>.<Olares-Domain des
// Nutzers> — 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);
+7 -2
View File
@@ -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",
+7 -2
View File
@@ -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",
+7 -2
View File
@@ -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",
+7 -2
View File
@@ -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",
+2 -2
View File
@@ -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.<n> 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.<n> 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
+2 -2
View File
@@ -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:
+5
View File
@@ -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.
+8
View File
@@ -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("<html>Anmelden</html>");
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 = '<think>hm</think>```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 () => {
+20
View File
@@ -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);
});
});