mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-16 15:23:29 +00:00
Admin, coach, consent, chart-overlay, device registration, insights feedback and provider chain, ECG ingest, onboarding, search and the AI provider settings move to parseJsonBody with the same message, error code, status and wide-event action they answered with. A refusal whose annotate meta is computed from the issues, or puts its keys in another order than the helper would, keeps that annotate verbatim in onInvalid. The routes that still call safeJson do something between the read and the schema: an optimistic-concurrency token split off the body, a count cap answered first, a refunded quota slot, a conditional read, a non-Zod check, or the body handed to a service.
157 lines
6.2 KiB
TypeScript
157 lines
6.2 KiB
TypeScript
import type { NextRequest } from "next/server";
|
|
import { apiHandler, HttpError, requireAuth } from "@/lib/api-handler";
|
|
import { apiSuccess } from "@/lib/api-response";
|
|
import { parseJsonBody } from "@/lib/api/body";
|
|
import { annotate } from "@/lib/logging/context";
|
|
import { probeProviderChain, resolveProviderChain } from "@/lib/ai/provider";
|
|
import {
|
|
forgetLastWorkingProvider,
|
|
getLastWorkingProvider,
|
|
} from "@/lib/ai/provider-runner";
|
|
import { prisma } from "@/lib/db";
|
|
import { parseProviderChain } from "@/lib/ai/provider-chain";
|
|
import { isReasoningProviderType } from "@/lib/ai/reasoning-effort";
|
|
import { providerChainPutSchema } from "@/lib/validations/ai-provider";
|
|
|
|
/**
|
|
* v1.4.16 — read-only chain summary for the Settings → AI
|
|
* section. Returns:
|
|
* - `activeProvider`: first entry in the resolved chain (priority
|
|
* order). Null when the user has no providers configured at all.
|
|
* - `cachedActiveProvider`: the last working provider from the
|
|
* in-process cache, when one is set. Surfaces "Active: codex
|
|
* (cached: openai)" so a user can see the runner has rerouted to
|
|
* a fallback without digging through logs.
|
|
* - `configuredChain`: ordered list of `{providerType, enabled,
|
|
* available}` entries. `available` is the presence probe's own
|
|
* answer for that entry's credential (`probeProviderChain`), enabled
|
|
* or not: an entry without a key, address or sign-in is listed but
|
|
* cannot answer, so a picker must not offer it.
|
|
*
|
|
* v1.4.16 phase B2 added the matching `PUT` for the new dropdown-driven
|
|
* settings UX — the user reorders/toggles entries in the section and
|
|
* the section persists the chain through this endpoint. The persisted
|
|
* shape lives on `User.aiProviderChain` (Json); a malformed payload
|
|
* from an out-of-date client cannot poison generation because every
|
|
* read goes through `parseProviderChain()`, which falls back to the
|
|
* default chain when given garbage.
|
|
*/
|
|
export const GET = apiHandler(async () => {
|
|
const { user } = await requireAuth();
|
|
|
|
// v1.4.16 (code-review H2) — the GET response used
|
|
// to surface the resolveProviderChain()-filtered list, which DROPS
|
|
// disabled entries. The Settings UI seeded `enabled: true` for every
|
|
// returned row, so disabling an entry made it disappear from the
|
|
// list and lose its toggle position. Read the *persisted* chain
|
|
// directly via parseProviderChain() so disabled rows still round-
|
|
// trip and the user can re-enable them. The active-provider summary
|
|
// still uses resolveProviderChain so the displayed "active = …"
|
|
// matches the actual runner ordering (enabled entries only).
|
|
const userRow = await prisma.user.findUnique({
|
|
where: { id: user.id },
|
|
select: { aiProviderChain: true },
|
|
});
|
|
const persisted = parseProviderChain(userRow?.aiProviderChain ?? null);
|
|
|
|
const [resolved, presence] = await Promise.all([
|
|
resolveProviderChain(user.id),
|
|
probeProviderChain(user.id),
|
|
]);
|
|
const availableTypes = new Set(presence.availableTypes ?? []);
|
|
const cached = getLastWorkingProvider(user.id);
|
|
|
|
annotate({
|
|
action: { name: "insights.provider_chain.get" },
|
|
meta: {
|
|
chain_length: persisted.length,
|
|
chain_enabled_count: persisted.filter((e) => e.enabled).length,
|
|
chain_active: resolved[0]?.providerType ?? null,
|
|
chain_cached_active: cached,
|
|
},
|
|
});
|
|
|
|
return apiSuccess({
|
|
activeProvider: resolved[0]?.providerType ?? null,
|
|
cachedActiveProvider: cached,
|
|
configuredChain: persisted.map((entry) => ({
|
|
providerType: entry.providerType,
|
|
enabled: entry.enabled,
|
|
available: availableTypes.has(entry.providerType),
|
|
})),
|
|
});
|
|
});
|
|
|
|
export const PUT = apiHandler(async (request: NextRequest) => {
|
|
const { user } = await requireAuth();
|
|
annotate({ action: { name: "insights.provider_chain.update" } });
|
|
|
|
const parsed = await parseJsonBody(request, providerChainPutSchema, {
|
|
maxBytes: 64 * 1024,
|
|
message: "Invalid provider chain payload",
|
|
});
|
|
if (!parsed.ok) return parsed.error;
|
|
|
|
// Defence-in-depth: reject duplicate provider types so a stale-tab
|
|
// resubmit cannot create a chain that walks the same entry twice.
|
|
// `parseProviderChain()` already deduplicates on read but we'd rather
|
|
// never persist a duplicate to begin with — drift between the two
|
|
// representations is the kind of bug that wastes an evening.
|
|
const seen = new Set<string>();
|
|
for (const entry of parsed.data.chain) {
|
|
if (seen.has(entry.providerType)) {
|
|
throw new HttpError(422, "Duplicate provider in chain");
|
|
}
|
|
seen.add(entry.providerType);
|
|
}
|
|
|
|
// Normalise priority to insertion order (1-based). UI hands us the
|
|
// visual order it wants persisted; we make priority match so a later
|
|
// GET reflects the same order without depending on the client's math.
|
|
//
|
|
// #1126 — a reasoning setting the body leaves out is carried over from the
|
|
// stored entry of the same type, so the chain editor (which only reorders
|
|
// and toggles) and an older client cannot wipe it by saving the order.
|
|
// `null` clears it; the schema has already refused it on any type other
|
|
// than `local` / `openai-compatible`.
|
|
const stored = await prisma.user.findUnique({
|
|
where: { id: user.id },
|
|
select: { aiProviderChain: true },
|
|
});
|
|
const storedEffort = new Map(
|
|
parseProviderChain(stored?.aiProviderChain ?? null).map((e) => [
|
|
e.providerType,
|
|
e.reasoningEffort ?? null,
|
|
]),
|
|
);
|
|
const normalised = parsed.data.chain.map((entry, idx) => {
|
|
const reasoningEffort = isReasoningProviderType(entry.providerType)
|
|
? entry.reasoningEffort === undefined
|
|
? (storedEffort.get(entry.providerType) ?? null)
|
|
: entry.reasoningEffort
|
|
: null;
|
|
return {
|
|
providerType: entry.providerType,
|
|
priority: idx + 1,
|
|
enabled: entry.enabled,
|
|
...(reasoningEffort ? { reasoningEffort } : {}),
|
|
};
|
|
});
|
|
|
|
await prisma.user.update({
|
|
where: { id: user.id },
|
|
data: { aiProviderChain: normalised },
|
|
});
|
|
forgetLastWorkingProvider(user.id);
|
|
|
|
annotate({
|
|
meta: {
|
|
chain_length: normalised.length,
|
|
chain_first: normalised[0]?.providerType ?? null,
|
|
chain_disabled_count: normalised.filter((e) => !e.enabled).length,
|
|
},
|
|
});
|
|
|
|
return apiSuccess({ saved: true });
|
|
});
|