mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-15 23:12:04 +00:00
The per-card status path capped provider generation at 20 s and, on timeout, persisted the generic no-key fallback as a day-keyed cache row. The cache-read only checked the day key and text, so that stub looked like a real assessment and stuck until midnight — hiding the real, data-driven text for the rest of the day on any account that hit a single transient stall. Align the budget with the provider clients' 60 s ceiling, route the status path through resolveProviderChain + runRawCompletionWithFallback so a degraded provider cascades like the coach, and stop persisting the fallback: a timeout or error is a transient miss that serves the fallback for the current render and re-attempts on the next mount. A shared cache-read rejects any lingering timeout-stub rows by their markers, and withTimeout now annotates real errors instead of folding them silently into the timeout path.
163 lines
5.5 KiB
TypeScript
163 lines
5.5 KiB
TypeScript
import { describe, expect, it, vi, beforeEach } from "vitest";
|
|
|
|
vi.mock("@/lib/db", () => ({
|
|
prisma: {
|
|
user: { findUnique: vi.fn() },
|
|
auditLog: { findFirst: vi.fn(), create: vi.fn() },
|
|
measurement: { findMany: vi.fn() },
|
|
moodEntry: { findMany: vi.fn() },
|
|
},
|
|
}));
|
|
|
|
vi.mock("@/lib/insights/status-provider", () => ({
|
|
runStatusCompletion: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("@/lib/insights/memory", () => ({
|
|
getPreviousInsightContext: vi.fn().mockResolvedValue(null),
|
|
formatPreviousContextForPrompt: vi.fn().mockReturnValue(""),
|
|
}));
|
|
|
|
import { prisma } from "@/lib/db";
|
|
import { runStatusCompletion } from "@/lib/insights/status-provider";
|
|
import { generatePulseStatusForUser } from "../pulse-status";
|
|
|
|
const dayMs = 24 * 60 * 60 * 1000;
|
|
|
|
function stubCompletion(
|
|
content: string,
|
|
capture?: { userPrompt: string | null },
|
|
) {
|
|
vi.mocked(runStatusCompletion).mockImplementation(
|
|
async (args: { userPrompt: string }) => {
|
|
if (capture) capture.userPrompt = args.userPrompt;
|
|
return {
|
|
kind: "ok",
|
|
content,
|
|
providerType: "anthropic",
|
|
model: "x",
|
|
tokensUsed: 1,
|
|
} as never;
|
|
},
|
|
);
|
|
}
|
|
|
|
beforeEach(() => {
|
|
vi.resetAllMocks();
|
|
});
|
|
|
|
describe("generatePulseStatusForUser — v1.4.6 bucketed payload", () => {
|
|
it("emits {daily, monthly} pulse series with dayOffset/monthOffset/value/n", async () => {
|
|
const now = new Date();
|
|
const records: Array<{ value: number; measuredAt: Date }> = [];
|
|
for (let day = 0; day < 1000; day++) {
|
|
records.push({
|
|
value: 70 + (day % 8),
|
|
measuredAt: new Date(now.getTime() - day * dayMs),
|
|
});
|
|
}
|
|
|
|
vi.mocked(prisma.user.findUnique).mockResolvedValue({
|
|
dateOfBirth: null,
|
|
gender: null,
|
|
} as never);
|
|
vi.mocked(prisma.auditLog.findFirst).mockResolvedValue(null);
|
|
vi.mocked(prisma.measurement.findMany).mockResolvedValue(records as never);
|
|
vi.mocked(prisma.moodEntry.findMany).mockResolvedValue([] as never);
|
|
vi.mocked(prisma.auditLog.create).mockResolvedValue({
|
|
createdAt: new Date(),
|
|
} as never);
|
|
|
|
const captured: { userPrompt: string | null } = { userPrompt: null };
|
|
stubCompletion('{"summary":"OK"}', captured);
|
|
|
|
await generatePulseStatusForUser("user-1", { locale: "en" });
|
|
|
|
const match = captured.userPrompt!.match(/\{[\s\S]*\}/);
|
|
const snapshot = JSON.parse(match![0]);
|
|
|
|
const pulse = snapshot.pulse.series;
|
|
expect(pulse).toHaveProperty("daily");
|
|
expect(pulse).toHaveProperty("monthly");
|
|
expect(pulse.daily.length).toBeGreaterThan(0);
|
|
expect(pulse.monthly.length).toBeGreaterThan(0);
|
|
expect(pulse.daily[0]).toHaveProperty("dayOffset");
|
|
expect(pulse.daily[0]).toHaveProperty("value");
|
|
expect(pulse.daily[0]).toHaveProperty("n");
|
|
expect(pulse.monthly[0]).toHaveProperty("monthOffset");
|
|
expect(pulse.monthly[0]).toHaveProperty("value");
|
|
expect(pulse.monthly[0]).toHaveProperty("n");
|
|
});
|
|
});
|
|
|
|
describe("generatePulseStatusForUser — cache-read skips a stub", () => {
|
|
it("regenerates when the only cached row is a timeout stub", async () => {
|
|
const now = new Date();
|
|
const todayKey = new Intl.DateTimeFormat("en-CA", {
|
|
timeZone: "Europe/Berlin",
|
|
}).format(now);
|
|
vi.mocked(prisma.user.findUnique).mockResolvedValue({
|
|
dateOfBirth: null,
|
|
gender: null,
|
|
} as never);
|
|
vi.mocked(prisma.auditLog.findFirst).mockResolvedValue({
|
|
createdAt: now,
|
|
details: JSON.stringify({
|
|
dateKey: todayKey,
|
|
locale: "en",
|
|
text: "Pulse fallback text…",
|
|
model: "timeout-stub",
|
|
timeout: true,
|
|
}),
|
|
} as never);
|
|
vi.mocked(prisma.measurement.findMany).mockResolvedValue([
|
|
{ value: 72, measuredAt: now },
|
|
] as never);
|
|
vi.mocked(prisma.moodEntry.findMany).mockResolvedValue([] as never);
|
|
vi.mocked(prisma.auditLog.create).mockResolvedValue({
|
|
createdAt: now,
|
|
} as never);
|
|
|
|
stubCompletion('{"summary":"Fresh pulse assessment."}');
|
|
|
|
const result = await generatePulseStatusForUser("user-1", { locale: "en" });
|
|
|
|
expect(runStatusCompletion).toHaveBeenCalledTimes(1);
|
|
expect(result.text).toBe("Fresh pulse assessment.");
|
|
expect(result.cached).toBe(false);
|
|
});
|
|
});
|
|
|
|
describe("generatePulseStatusForUser — token-leak hardening (v1.4.27 F16)", () => {
|
|
it("strips metric: tokens out of the cached text before persisting", async () => {
|
|
vi.mocked(prisma.user.findUnique).mockResolvedValue({
|
|
dateOfBirth: null,
|
|
gender: null,
|
|
} as never);
|
|
vi.mocked(prisma.auditLog.findFirst).mockResolvedValue(null);
|
|
vi.mocked(prisma.measurement.findMany).mockResolvedValue([
|
|
{ value: 72, measuredAt: new Date() },
|
|
] as never);
|
|
vi.mocked(prisma.moodEntry.findMany).mockResolvedValue([] as never);
|
|
vi.mocked(prisma.auditLog.create).mockResolvedValue({
|
|
createdAt: new Date(),
|
|
} as never);
|
|
|
|
stubCompletion(
|
|
'{"summary":"Your pulse is stable. metric:PULSE The 7-day average sits inside the band."}',
|
|
);
|
|
|
|
const result = await generatePulseStatusForUser("user-1", { locale: "en" });
|
|
|
|
expect(result.text).toBeTruthy();
|
|
expect(result.text).not.toContain("metric:");
|
|
const createCalls = vi.mocked(prisma.auditLog.create).mock.calls;
|
|
expect(createCalls.length).toBeGreaterThan(0);
|
|
const details = (createCalls[0][0] as { data: { details: string } }).data
|
|
.details;
|
|
const parsed = JSON.parse(details) as { text: string };
|
|
expect(parsed.text).not.toContain("metric:");
|
|
expect(parsed.text).toContain("Your pulse is stable.");
|
|
});
|
|
});
|